Tuesday, April 28, 2009

Custom Events in Flex Part II

In the following example the component is loosely coupled with the Application. The communication (and data transfer) happening through the custom events.



CustomEvent Class

=================



package com

{

import flash.events.Event;



public class MyButtonEvent extends Event

{

public static const MY_EVENT:String = "myevent";

        public var myBtnId:String;

        

        

        // create static cosnst for evetn name

        // and add public property to store button id

        // and finally override the clone method

        

        

public function MyButtonEvent(type:String, myBtnId:String)

{

super(type);

this.myBtnId = myBtnId;

}

        

        

        override public function clone():Event {

            return new MyButtonEvent(type, myBtnId);

        }



}

}



Component

===============



<?xml version="1.0" encoding="utf-8"?>

<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="166" height="80">

<mx:Metadata>

       [Event(name="myevent",type="com.MyButtonEvent")]

    </mx:Metadata>

<mx:Script>

<![CDATA[





private function clickHandler(e:MouseEvent):void

{

var objEve:MyButtonEvent = new MyButtonEvent("myevent",e.currentTarget.id)

dispatchEvent(objEve);

}





]]>

</mx:Script>

<mx:Button id="btn" x="47.5" y="30" label="Click Me" click="clickHandler(event)"/>



</mx:Canvas>



And the Application

=================





<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:com="com.*">



<mx:Script>

<![CDATA[

import com.MyButtonEvent;

import mx.controls.Alert;



private function myeventHandler(e:MyButtonEvent):void

{

Alert.show(e.myBtnId)

}



]]>

</mx:Script>

<com:MyComp myevent="myeventHandler(event)" x="373" y="61"/>

</mx:Application>




No comments: