Saturday, December 10, 2011

Flex: Building Custom Event (an example)


Events are a real powerful tool inside every programming language that has them. In ActionScript, there are a lot of standard events that you are probably already using (e.g. the click event).

But what if you want to do something custom with an event inside your flex application? Let’s say you have created a custom component and you want to dispatch an event from that component with some additional data? Check out this example to see how you can achieve this.

Although I may not make any sense, let’s say I want to do the following:
  • Have a component that gets data when a button is pressed.
  • Have an Application that’s using this component and reacts when the data is loaded inside the component mentioned above.
I’ll need three things for this:
  1. A custom event that transports the data and lets my application know that the data is loaded.
  2. The component.
  3. The Application.

Step 1: Create the custom Event:

 package com.tm.examples.events
{
    import flash.events.Event;
    import mx.collections.ArrayCollection;
    
    public class CustomEvent extends Event
    {
        
        public static var DATA_LOADED:String = "dataLoaded";
        
        private var _data:ArrayCollection;
        
        public function CustomEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=falsedata:ArrayCollection=null)
        {
            super(type, bubbles, cancelable);
            _data = data;
        }
        
        override public function clone():Event
        {
            return new CustomEvent(type, bubbles, cancelable, data);
        }
        
        public function get data():ArrayCollection
        {
            return _data;
        }
    }
}


Step 2: Create the component that gets some data and dispatches this event:

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="300" height="300" backgroundAlpha="0">
    <mx:Metadata>
        [Event(type="com.tm.examples.events.CustomEvent"name="dataLoaded")]
    </mx:Metadata>
    <mx:Script>
        <![CDATA[
            import com.tm.examples.events.CustomEvent;
            import mx.collections.ArrayCollection;
            
            private function handleClick():void
            {
                var data:ArrayCollection = getData();
                dispatchEvent( new CustomEvent( CustomEvent.DATA_LOADEDfalsefalsedata ) );
            }
            
            private function getData():ArrayCollection
            {
                var obj:Object;
                var dataCollection:ArrayCollection = new ArrayCollection();
                for( var i:int=0; i < 10; i++ )
                {
                    obj = new Object();
                    obj.index = i;
                    obj.value = Math.round(Math.random() * 100);
                    dataCollection.addItem(obj);
                }
                return dataCollection;
            }
        ]]>
    </mx:Script>
    <mx:VBox width="100%" height="100%" verticalAlign="middle" horizontalAlign="center">
        <mx:Button label="Get Data and Dispatch Event!" click="handleClick()"/>
    </mx:VBox>
</mx:Canvas>

Step 3: Create the application that reacts to the event and does something with the data:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
                layout="absolute"
                xmlns:components="com.tm.examples.components.*">
    <mx:Script>
        <![CDATA[
            import com.flexblog.examples.events.CustomEvent;

            private function handleDataLoaded(event:CustomEvent):void
            {
                dg.dataProvider=event.data;
            }
        ]]>
    </mx:Script>

    <mx:VBox width="100%"
             height="100%"
             backgroundColor="#FFFFFF"
             horizontalAlign="center">
        <components:ExampleComponent width="300"
                                     height="100"
                                     dataLoaded="handleDataLoaded(event)"/>
        <mx:DataGrid id="dg"
                     width="300"
                     height="200"
                     visible="{dg.dataProvider != null}">
            <mx:columns>
                <mx:DataGridColumn dataField="index"
                                   headerText="Index"/>
                <mx:DataGridColumn dataField="value"
                                   headerText="Value"/>
            </mx:columns>
        </mx:DataGrid>
    </mx:VBox>
</mx:Application>