Monday, April 27, 2009

Custom Events in Flex Part I

Flex applications are event-driven. Events let an application know when the user interacts with the interface, and also when important changes happen in the appearance or life cycle of a component, such as the creation of a component or its resizing. Events can be generated by user input devices, such as the mouse and keyboard, or by the asynchronous operations, such as the return of a web service call or the firing of a timer.

In addition to using the events inherited from its superclasses, your custom components can define custom events. You use custom events to support data binding, to respond to user interactions, or to trigger actions by your component.

When a Flex component dispatches an event, it creates an event object, where the properties of the event object contain information describing the event. An event listener takes this event object as an argument and accesses the properties of the object to determine information about the event.

The base class for all event objects is the flash.events.Event class. All event objects are instances of the Event class, or instances of a subclass of the Event class.

Here is the simple example of dispatching a custom event from an custom component.



<?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 mx.controls.Alert;



private function myeventHandler(e:Event):void

{

Alert.show('myevent')

}



]]>

</mx:Script>

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

</mx:Application>







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="flash.events.Event")]

    </mx:Metadata>



<mx:Button x="47.5" y="30" label="Click Me" click="dispatchEvent(new Event('myevent'));"/>



</mx:Canvas>

No comments: