Simple tip #1 – custom events

Simple tip #1 – custom events

Today while coding I was creating some classes that required them to dispatch custom events. I know that this is a fairly common thing to do but sometimes it is these little things that can trip you up or take a while to find out how to do them.

So I thought that each time I come across something that is ‘simple’ (only simple after you know it!) that I’ll try to create a quick blog entry and take note of it.  Each time I create a new ‘tip’ post I’ll link it to the previous/next tip so that it will be quick and easy to browse through a load of tips.
 

Tip #1

So for my first tip, this is how to implement your own custom events.

First if you are firing the events from a custom MXML file then you need to create a metadata tag. I make this the first node inside the MXML file.  For example:

 







	[Event('next')]
	[Event('previous')]
	[Event(name='jump', type='com.kennethsutherland.events.JumpEvent')]

...

If your custom class is an AS3 file then you would put something like the following are the imports

[Event(name="previous", type="flash.events.Event")]
[Event(name='jump', type='com.kennethsutherland.events.JumpEvent')]

Then inside the MXML file (script block) or anywhere in the AS3 file to fire the event I’d do the following:
 

//custom event, the extra value is handled by the JumpEvent class
dispatchEvent(new JumpEvent("jump", specificValueForTheJumpEventClass));
//standard event
dispatchEvent(new Event("next")); 

If you do the above and lets just say your MXML/AS file is called ‘GreatComponent’ then in order to use the new custom event, its as simple as the below bit of code. 


That’s it, now you can fire of any custom event that you wish and make sure that it gets listened to.

Next Tip

 

[ad name=”ad-1″]

Leave a Reply

Your e-mail address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.