Follow Flex After Dark on Twitter

Events in Flex

Events are everywhere in Flex. Everything interesting that happens in a Flex application is represented by or the result of an event.

Each time the mouse is moved or clicked, or a key is pressed on the keyboard an event is dispatched. But events are not just limited to "system" type events from the mouse and keyboard. Events are also generated for important "business" type events and application state changes.

Flex applications are event-driven, meaning that ActionScript responds to interactions by dispatching events, and expects a program to listen to interesting events. Programs interested in certain events will register event listeners and execute code when those events are received.

If you've done much JavaScript programming in HTML, you've probably already dealt with events.

Let's see some event handling in action.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
   <mx:Script>
      <![CDATA[
         import mx.controls.Alert;
         
         // 2. This function is notified when the "click" event occurs.
         public function clickHandler( event:Event ):void
         {
            // 3. In response to the event an alert message is shown.
            Alert.show( "Button clicked" );
         }
      ]]>

TODO: embed example: X_Events1
   </mx:Script>
   
   <!-- 1. Click on the button to announce the "click" event. -->
   <mx:Button label="Click Me" click="clickHandler(event)"
      horizontalCenter="0" verticalCenter="0" />
</mx:Application>

Important event participants:

  • dispatcher - the subject of the event
  • event - the event object encapsulating details of the event occurence
  • listener - the handler function for dealing with an event

In the above example, the Button is the dispatcher. When a user clicks on the button, it dispatches (announces) a "mouse click" event. Information about the occurence is encapsulated in the event object. Such information includes: the type ("click"), the target (the button), and much more. The "clickHandler()" function is the listener that gets notified when the click event occurs. Note that the event object is passed as an argument to the listener function.

Another Example

Here's another example that looks and behaves exactly like the one above. However, the code behind it is a little different.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
   creationComplete="init()">
   <mx:Script>
      <![CDATA[
         import mx.controls.Alert;
         
         // This function is called when the "creationComplete" event occurs.
         public function init():void
         {
            // Register the clickHandler() listener with the button.
            this.button.addEventListener( MouseEvent.CLICK, clickHandler );
         }
         
         // This function is notified when the "click" event occurs.
         public function clickHandler( event:Event ):void
         {
            // In response to the event an alert message is shown.
            Alert.show( "Button clicked" );
         }
      ]]>
   </mx:Script>
   
   <!-- Click on the button to announce the "click" event. -->
   <mx:Button id="button" label="Click Me"
      horizontalCenter="0" verticalCenter="0"/>
</mx:Application>

Let's look at some key things we've done in the above example.

1. On line 3, we are telling the application to call the init() function when the creationComplete event occurs.

2. Inside the init() function we are registering an event listener for the button. The event type we're listening for is MouseEvent.CLICK, which is just a constant for the string "click". The listener we are registering is the clickHandler function.

Note that we are referencing the function, not calling it, so we don't need "()" parantheses. We can do this because in ActionScript Functions are first-class objects.

3. In the <mx:Button> declaration we've removed the click="clickHandler(event)" code. This type of event-listener binding is a convenient short-hand provided by Flex (MXML). The listener registeration we've done in the init() function (ActionScript) has the exact same affect.

4. Something we haven't done is change the clickHandler() function. Even though we are registering it as an event listener in a different way, the function is still called in the same way.

Event API and Classes

Event (flash.events.Event)

Each event is an instance of the flash.events.Event ActionScript class, or sub-class.

Important Event properties:

  • type - the type of event that occurred (e.g. button click, mouse move, child added)
  • target - the subject of the event
  • currentTarget - object that is actively processing the Event object with an event listener

Don't confuse an Event's type (a string such as "click") with its class or the object-oriented concept of type.

Event Dispatcher (flash.events.IEventDispatcher)

The EventDispatcher class is the base class for all classes that dispatch events. The IEventDispatcher interface and base EventDispatcher class are defined in the flash.events package.

The IEventDispatcher interface defines several functions, but the two key methods are:

  • dispatchEvent() - dispatches an event into the event flow so that registered listeners are notified
  • addEventListener() - registers an event listener object so that the listener receives notification of dispatched event

Learn more about the Event Dispatcher interface and class...

Event Lifecycle: Listening, Dispatching, and Handling

Important event participants:

  • dispatcher - the subject of the event
  • event - the event object encapsulating details of the event occurence
  • listener - the handler function for dealing with an event

Listening for Events

Listening for an event involves registering a callback or handler function with an event dispatcher.

   // register a handler function as an event listener
   dispatcher.addEventListener( "eventType", handlerFunction );

Dispatching Events

Dispatching an event happens when something interesting occurs that an event dispatcher wants to notify listeners of.

   // dispatch an event to my listeners
   dispatchEvent( new Event( "eventType" ) );

Handling Events

Handling and event is the result of an event dispatcher calling a callback or handler function of a listener in response to an event.

   // handle an event in a listener
   public function handlerFunction( event:Event ):void
   {
      ...
   }

Event Bubbling and the DOM

Generally, UI events within Flash bubble up from inner-most components up through container objects, triggering events for each container along the way. A click on a DisplayObject, for example, may trigger an event MouseEvent.MOUSE_DOWN on that object, and then pass that event up the hierarchy to any containing elements and their listeners.

Flex creates only one Event object when an event is dispatched. During the bubbling and capturing phases, Flex changes the values on the Event object as it moves up or down the display list, rather than creating a new Event object for each node.

Event targets are an important part of the Flash Player and Adobe AIR event model. The event target serves as the focal point for how events flow through the display list hierarchy. When an event such as a mouse click or a key press occurs, Flash Player or the AIR application dispatches an event object into the event flow from the root of the display list. The event object then makes its way through the display list until it reaches the event target, at which point it begins its return trip through the display list. This round-trip journey to the event target is conceptually divided into three phases: the capture phase comprises the journey from the root to the last node before the event target's node, the target phase comprises only the event target node, and the bubbling phase comprises any subsequent nodes encountered on the return trip to the root of the display list.

Related Links:

Related Docs
Recent Docs
  • Flex Events Events drive Flex applications. See how to register listeners and dispatch events.
  • Flex Text Controls Flex Text Controls allow the display and input of simple and rich HTML text.
  • ActionScript Language Introduction to the ActionScript 3.0 programming language.
  • Flex Validators Flex Validators are used for validating user-input data.
  • ActionScript XML ActionScript has powerful XML support via E4X.
Random Docs
  • Object-Oriented ActionScript ActionScript is a full-featured Object-Oriented language with support for classes, interfaces, encapsulation, polymorphism, and inheritance.
  • Flex Date Controls Flex Date Controls allow users to select dates and date ranges with DateField and DateChooser.
  • Flex Text Controls Flex Text Controls allow the display and input of simple and rich HTML text.
  • Flex Builder Keyboard Shortcuts Flex Builder Keyboard Shortcuts
  • Flex Remoting Flex Remoting and the RPC package provide robust, asynchronous communication with remote servers via HTTP and Web Services.