Custom Events – I


Posted By : Oliver Merk
Related Categories: Flex,AIR

This is one of those areas that a lot of Flex developers I’ve talked to tend to avoid. The idea behind a custom event is that you create them inside your components so that you can broadcast the event up to the main application file of your Flex app. Why? The main reason is so that you can de-couple your components by putting the event-handling logic somewhere outside of the component. This makes your component easier to test and more re-usable. Finally, it is one way to implement a Front Controller/Command pattern (more on that in a future post).

Creating a custom event and then broadcasting it requires several steps. Read more…

Step 1: In the component, declare the name (type) of the custom event:

<mx:Metadata>
[ Event( name=“myCustomEvent”, type=“flash.events.Event”) ]
</mx:Metadata>

Notice that you can call your event whatever you want, though you cannot override an event already defined in the Flex API. So instead of an event called “click”, your application can respond to something more indicative like “addProduct” or “registerUser”.

Step 2: In response to some user event, like a button click, call a function that creates the object and then dispatches it. Note that we’re still inside the component at this point.

private function onButtonClick():void {

// create your new event object
var myEventObj:Event = new Event( “myCustomEvent” );

// broadcast the event to whomever may be listening
dispatchEvent( myEventObj );
}

Step 3: In the parent of the component, add the event listener to the invocation of the custom component.

<comp:MyComponent id=“myComponent” myCustomEvent=“onMyCustomEvent( event );” />

Step 4: Write the custom event handler in the parent component. In this case the handler would look something like this:

private function onMyCustomEvent( event:Event ):void
{
mx.controls.Alert.show(‘I heard that!’);
}
Advertisements

~ by mjcprasad2000 on July 11, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: