Sunday, July 16, 2006

Flex 2: Events Made Easy

I've put together a quick and easy example how to define custom events that will be dispatched from a Flex component. Its pretty easy really... This example just contains 2 custom components. One component is created with MXML and the other is created with ActionScript. Both extend the mx.controls.Button class. When the button is clicked, each dispatches a "customevent" type event.

Here's the example:



And here's how it is done...
For a component to dispatch an event, the event has to be declared within the component.

  • In MXML:
    <mx:Metadata>>[Event("customevent")]</mx:Metadata>

  • In ActionScript:
    [Event(name="customevent", type="flash.events.Event")]

In order to dipatch my "customevent" type of event, the component (internally) just needs to create an event and dispatch it:
this.dispatchEvent( new Event("customevent") );

Now that you have the custom event defined, you can add a listener to it straight from you mxml declaraion. Just add actionscript to the customevent event that we just created:
<ExampleMXMLComponent id="MXMLcomp" customevent="Alert.show(event.target.toString());" x="10" top="10"/>

If you want to pass data back and forth using this event, you could simply extend the event class, then create & dispatch the custom event type instead of a standard flash.events.Event;.

View the source for this example.
Download the source for this example.

2 Comments:

Blogger Jeremy said...

thank you thank you!

Wed Jul 25, 09:57:00 AM EDT  
Blogger Taher M said...

Thank you very much

Mon Feb 11, 07:39:00 AM EST  

Post a Comment

<< Home