Accessibility

ActionScript Article

 

Introduction to event handling in ActionScript 3.0


Table of Contents

Event handling in ActionScript 3.0 depends heavily on the EventDispatcher class. Although this class isn't entirely new to ActionScript, it is the first time it has been included as a core part of the ActionScript language. You may also be familiar with EventDispatcher from JavaScript or ActionScript 2.0 when using V2 components. With V2 components, an external version of the EventDispatcher class was used to handle component events. This version is slightly different from the version of EventDispatcher used internally by ActionScript 3.0.

For those not familiar with EventDispatcher, the basic concept is this: First you create functions, or event handlers, to react to various events. Then you associate those functions with the events by using the addEventListener() method, which is called from the object that will receive the event. This is similar to the normal, core process in ActionScript 2.0 (not using EventDispatcher). The difference is that in ActionScript 2.0, you define the event handler within the object receiving the event—giving the function the name of the event being received. For example, to react to an "onPress" event for a button named submitButton in ActionScript 2.0, you would use:

submitButton.onPress = function() { ... }

Using EventDispatcher, the same elements are at play; an object receiving an event, an event name, and a function that reacts to an event—only the process is slightly different. The code using EventDispatcher looks like this:

function pressHandler(){ ... }
submitButton.addEventListener("onPress", pressHandler);

This process adds what appears to be an extra step, but it allows for more flexibility. Since you are using a function to add event handlers instead of defining them directly on the target object itself, you can now add as many handlers as you like to "listen" to a single event.

Removing events in ActionScript 2.0 just meant deleting the handler:

delete submitButton.onPress;

Using EventDispatcher, you use removeEventListener(). This method removes an event listener that matches the same definition used in addEventListener (up to the third parameter).

submitButton.removeEventListener("onPress", pressHandler);

Where is EventDispatcher?

You may have noticed that the code snippets above do not explicitly reference EventDispatcher. In fact, it's rare that you would ever use EventDispatcher directly in your code. EventDispatcher, in ActionScript 3.0, is actually a base class, which other classes extend in order to be able to have access to addEventListener and other EventDispatcher methods. In ActionScript 2.0, EventDispatcher was a mixin class.

This meant in order for it to give these methods to other objects, EventDispatcher.initialize() was used to copy them from EventDispatcher into the desired object. Now classes just inherit the methods by extending EventDispatcher. Luckily most classes that need to use EventDispatcher in ActionScript 3.0, like MovieClip and other DisplayObjects already extend EventDispatcher making it accessible and easy to use (though if necessary, advanced users can also include EventDispatcher functionality through composition).

EventDispatcher methods

Here is a summary of the methods in EventDispatcher for ActionScript 3.0. Many of these methods are similar to the methods in the ActionScript 2.0 version:

  • addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
  • removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
  • dispatchEvent(event:Event):Boolean
  • hasEventListener(type:String):Boolean
  • willTrigger(type:String):Boolean

If you are familiar with ActionScript 2.0, you'll notice that there are two new methods, hasEventListener and willTrigger. Additionally, addEventListener for ActionScript 3.0 now only allows functions as listeners, not objects (objects could be used as listeners in the older version). Since methods are now bound to their instances in ActionScript 3.0, there is essentially no need to use objects for listeners anymore. This means that the this keyword in a function will always correctly reference the instance to which it was obtained. It also eliminates the need for the ActionScript 2.0 Delegate class.

  • addEventListener(): Adds an event handler function to listen to an event so that when that event occurs, the function will be called.
  • removeEventListener(): Removes an event handler added to a listeners list using addEventListener. The same first 3 arguments used in addEventListener must be used in removeEventListener to remove the correct handler.
  • dispatchEvent(): Sends the passed event to all listeners in the listeners list of an object that relates to the event type. This method is most commonly used when creating custom events.
  • hasEventListener(): Determines whether or not an object has listeners for a specific type of event.
  • willTrigger(): Determines whether or not an object or any of its parent containers have listeners for a specific type event. This is much like hasEventListener but this method checks the current object as well as all objects that might be affected from the propagation of the event.

These methods, as well as any other function or method in ActionScript 3.0 language, can also be found in the ActionScript 3.0 Language Reference.

Example 1: Clicking a box

As a simple example, consider clicking on a square instance named "box" on the screen (see Figure 1). The goal of this example is to handle that event so that the text "click" is traced in the Output panel when the box is clicked with the mouse.

Clicking on the box instance causes the word "click" to appear in the Output panel

Figure 1. Clicking on the box instance causes the word "click" to appear in the Output panel

To create this test movie, do the following:

Using Flash CS3 Professional

  1. Create a new Flash document.
  2. Create a square movie clip on the screen.
  3. Give the square an instance name of box.
  4. Add the following timeline script in Frame 1:

    function clickHandler(event:MouseEvent):void {
       trace("click");
    }
    
    box.addEventListener(MouseEvent.CLICK, clickHandler);
    

Using Flex 3

  1. Create a new Flex MXML document.
  2. Use the following MXML:

    <?xml version="1.0" encoding="utf-8"?>
    "mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
                applicationComplete="initApp()""
       <mx:Script>
          "![CDATA[
             public function clickHandler(event:MouseEvent):void {
                trace("click");
             }
             public function initApp():void {
                box.addEventListener(MouseEvent.CLICK, clickHandler);
             }
          ]]"
       </mx:Script>
       
       <mx:Canvas id="box" width="200" height="200" backgroundColor="#800000">
       </mx:Canvas>
       
    </mx:Application>
    

Let's take a look at the script. The first step is to define the event handler (listener function). As with all events, this accepts in its parameter list a single event instance that's automatically passed into the function when called from an event dispatcher. After that, the function is set as a listener to the box instance—the event dispatcher—listening for a MouseEvent.CLICK event using a basic addEventListener call (this occurs in the initApp method in Flex). Since the box is an instance of MovieClip (Canvas in Flex) it inherits from EventDispatcher and has access to all the EventDispatcher methods, including addEventListener.

MouseEvent.CLICK is a constant variable defined in the MouseEvent class. It simply provides the string of the event; for MouseEvent.CLICK that's "click." Other event types are also stored in similar constants in the MouseEvent class, as well as other event-related classes. Note that many of these have changed compared to their own ActionScript 2.0 counterparts. For example, rather than using the onPress event in ActionScript 2.0, you would use MouseEvent.MOUSE_DOWN (or "mouseDown") in ActionScript 3.0. You can find more of these distinctions within the ActionScript 3.0 Language Reference in the events package and in the different Event classes that exist within that package.

For this example you could just as easily have used "click" instead of MouseEvent.CLICK, but using these constants helps you detect typos in your code. Mistyping the string "click," for example, would not result in a compile-time error since, as a string, Flash has no way of knowing whether or not its contents are accurate. If you misspell MouseEvent.CLICK, however, Flash will be able to recognize the error and can throw a compile-time error. Most event classes have these constants that relate to their event type strings. It is highly recommended that you use them instead of the actual string itself.

Testing the movie will display a clickable box that, when clicked, traces the word "click".

Note: Flex users should be sure to test the movie using Debug so that the trace output can be captured by Flex Builder.