Adobe Flex 3 Help

Using events

Using events in Flex is a two-step process. First, you write a function or class method, known as an event listener or event handler, that responds to events. The function often accesses the properties of the Event object or some other settings of the application state. The signature of this function usually includes an argument that specifies the event type being passed in.

The following example shows a simple event listener function that reports when a control triggers the event that it is listening for:

<?xml version="1.0"?>
<!-- events/SimpleEventHandler.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="initApp();">
    <mx:Script><![CDATA[
        import mx.controls.Alert;

        private function initApp():void {
            b1.addEventListener(MouseEvent.CLICK, myEventHandler);
        }

        private function myEventHandler(event:Event):void {
            Alert.show("An event occurred.");
        }
    ]]></mx:Script>

    <mx:Button id="b1" label="Click Me"/>

</mx:Application>

The executing SWF file for the previous example is shown below:

As you can see in this example, you also register that function or class method with a display list object by using the addEventListener() method.

Most Flex controls simplify listener registration by letting you specify the listener inside the MXML tag. For example, instead of using the addEventListener() method to specify a listener function for the Button control's click event, you specify it in the click attribute of the <mx:Button> tag:

<?xml version="1.0"?>
<!-- events/SimplerEventHandler.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script><![CDATA[
        import mx.controls.Alert;

        private function myEventHandler(event:Event):void {
            Alert.show("An event occurred.");
        }
    ]]></mx:Script>

    <mx:Button id="b1" label="Click Me" click="myEventHandler(event)"/>

</mx:Application>

The executing SWF file for the previous example is shown below:

This is equivalent to the addEventListener() method in the previous code example. However, it is best practice to use the addEventListener() method. This method gives you greater control over the event by letting you configure the priority and capturing settings, and use event constants. In addition, if you use addEventListener() to add an event handler, you can use removeEventListener() to remove the handler when you no longer need it. If you add an event handler inline, you cannot call removeEventListener() on that handler.

Each time a control generates an event, Flex creates an Event object that contains information about that event, including the type of event and a reference to the dispatching control. To use the Event object, you specify it as a parameter in the event handler function, as the following example shows:

<?xml version="1.0"?>
<!-- events/EventTypeHandler.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script><![CDATA[
        import mx.controls.Alert;

        private function myEventHandler(e:Event):void {
            Alert.show("An event of type '" + e.type + "' occurred.");
        }
    ]]></mx:Script>

    <mx:Button id="b1" label="Click Me" click="myEventHandler(event)"/>

</mx:Application>

The executing SWF file for the previous example is shown below:

If you want to access the Event object in an event handler that was triggered by an inline event, you must add the event keyword inside the MXML tag so that Flex explicitly passes it to the handler, as in the following:

<mx:Button id="b1" label="Click Me" click="myEventHandler(event)"/>

You are not required to use the Event object in a handler function. The following example creates two event handler functions and registers them with the events of a ComboBox control. The first event handler, openEvt(), takes no arguments. The second event handler, changeEvt(), takes the Event object as an argument and uses this object to access the value and selectedIndex of the ComboBox control that triggered the event.

<?xml version="1.0"?>
<!-- events/MultipleEventHandlers.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script><![CDATA[
        private function openEvt():void {
            forChange.text="";
        }

        private function changeEvt(e:Event):void {
            forChange.text = 
            "Value: " + e.currentTarget.value + "\n" +
            "Index: " + e.currentTarget.selectedIndex;
        }
    ]]></mx:Script>

    <mx:ComboBox open="openEvt()" change="changeEvt(event)">
        <mx:dataProvider>
            <mx:Array>
                <mx:String>AK</mx:String>
                <mx:String>AL</mx:String>
                <mx:String>AR</mx:String>
            </mx:Array>
        </mx:dataProvider>
    </mx:ComboBox>

    <mx:TextArea id="forChange" width="150" height="100"/>

</mx:Application>

The executing SWF file for the previous example is shown below:

This example shows accessing the target property of the Event object. For more information, see Accessing the currentTarget property.

Specifying the Event object

You specify the object in a listener function's signature as type Event, as the following example shows:

function myEventListener(e:Event):void { ... }

However, if you want to access properties that are specific to the type of event that was dispatched, you must instead specify a more specific event type, such as ToolTipEvent or KeyboardEvent, as the following example shows:

import mx.events.ToolTip
function myEventListener(e:ToolTipEvent):void { ... }

In some cases, you must import the event's class in your ActionScript block.

Most objects have specific events that are associated with them, and most of them can dispatch more than one type of event.

If you declare an event of type Event, you can cast it to a more specific type to access its event-specific properties. For more information, see Using event subclasses.

Accessing the currentTarget property

Event objects include a reference to the instance of the dispatching component (or target), which means that you can access all the properties and methods of that instance in an event listener. The following example accesses the id of the Button control that triggered the event:

<?xml version="1.0"?>
<!-- events/AccessingCurrentTarget.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script><![CDATA[
        import mx.controls.Alert;

        private function myEventHandler(e:Event):void {
            Alert.show("The button '" + e.currentTarget.id + "' was clicked.");
        }
    ]]></mx:Script>

    <mx:Button id="b1" label="Click Me" click="myEventHandler(event)"/>

</mx:Application>

The executing SWF file for the previous example is shown below:

You can access members of the currentTarget. If you do not cast the current target to a specific type, the compiler assumes that it is of type Object. Objects can have any property or method because the Object type is dynamic in ActionScript. Therefore, when accessing methods and properties of the currentTarget, it is best practice to cast currentTarget to whatever class you anticipate will dispatch that event. This gives you strong type checking at compile time, and helps avoid the risk of throwing a run-time error.

The following example casts the current target to a TextInput class before calling the setSelection() method, but does not cast it before trying to set the tmesis property. The tmesis property does not exist on the TextInput class. This illustrates that you will get a run-time error but not a compile-time error when you try to access members that don't exist, unless you cast currentTarget to a specific type so that type checking can occur:

<?xml version="1.0"?>
<!-- events/InvokingOnCurrentTarget.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Script><![CDATA[
     import mx.core.UIComponent;

     private function tiHandler(e:Event):void {
        /* The following enforces type checking: */
        TextInput(e.currentTarget).setSelection(0,3);
        
        /* The following throws a run-time error but not a compile-time error: 
        e.currentTarget.tmesis = 4;
        */
        
        /*
        ... unless you cast it to the expected type like the following. Then
        the compiler throws an error.
        TextInput(e.currentTarget).tmesis = 4; 
        */
     }
     
  ]]></mx:Script>

  <mx:TextInput id="ti1" click="tiHandler(event)"
        text="This is some text. When you click on this control, the first three characters are selected."/>

</mx:Application>

The executing SWF file for the previous example is shown below:

You could also cast currentTarget to UIComponent or some other more general class that still has methods of display objects. That way, if you don't know exactly which control will dispatch an event, at least you can ensure there is some type checking.

You can also access methods and properties of the target property, which contains a reference to the current node in the display list. For more information, see About the target and currentTarget properties.