Pages

Thursday, 29 March 2012

Event Handling in Flex

Event Listeners

Terms to know:
  • eventType: Event type broadcast by the object when an event occurs. This is represented as a String data type.
  • event listener: The function or class method that you write to respond to specific events. They're also known as event handlers.
When an event occurs, Flex creates an event object where the properties of the event object contain information describing the event
  • ActionScript gives you advanced event handling features
  • The addEventListener() method of the EventDispatcher class permits you to register event handler functions for a specified object
  • Allows greater control over the event by letting you configure the priority and capturing settings
  • Adding a listener by ActionScript also allows you to use removeEventListener() to remove the handler when you no longer need it

VBoxDemo.mxml


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    name="DemoApplication"
    backgroundColor="#FFFFFF"
    backgroundAlpha="0"
    creationComplete="initApp()"
    >

    <mx:Script>
        <![CDATA[
            import flash.events.EventPhase
            import mx.controls.Alert;

            private function initApp():void {
                myVBox2.addEventListener("click", myHandleClick);
                myVBox3.addEventListener("click", myHandleClick2);
            }

            private function myHandleClick(event:Event):void {
                label1.text = "You clicked VBox 2";
            }

            private function myHandleClick2(event:Event):void {
                myVBox2.removeEventListener("click",myHandleClick);
                label1.text = "";
            }

       ]]>
    </mx:Script>
    <mx:Label text="Application"/>

    <mx:VBox id="myVBox1"
        backgroundColor="#FFCCFF"
        width="300" height="100"
        horizontalAlign="center">

        <mx:Label text="VBox 1" />

    </mx:VBox>

    <mx:VBox id="myVBox2"
        backgroundColor="#FFCCCC"
        width="300" height="100"
        horizontalAlign="center">

    <mx:Label text="VBox 2" />

    </mx:VBox>

    <mx:VBox id="myVBox3"
        backgroundColor="#FFFFCC"
        width="300" height="100"
        horizontalAlign="center">

        <mx:Label text="VBox 3" />

    </mx:VBox>
    <mx:Label id="label1"
        width="80%" height="48"
        fontWeight="bold" />

</mx:Application>

 

Rendered Example

  • VBox 1: No listener registered
  • VBox 2: Listener registered when application initialized. The event handler will display a Label component when there is a click event
  • VBox 3: Listener registered when application initialized. The event handler will remove the listener from VBox 1 and clear the Label text when there is a click event.
If you have clicked Vbox3, clicking VBox 2 will not display the Label component because the event listener has been removed.


 

No comments:

Post a Comment