ActionScript 3 Custom Event Base Class

I still see a steady stream of  questions on Flex and ActionScript discussion boards related to effectively using custom events. I can tell you from many hours of experience that custom events are the fundamental basis for transmitting information in any mildly complex Flex/AS3 project and whether they’re Notifications in PureMVC or the wiring for Mate or simply vanilla using something like Swiz (my favorite) and you should be using them.

Problem

You’ve heard about custom events in AS3 but don’t really understand them or are interested in best practice uses for them.

Solution

Typically the most common need for a true custom event is to transmit some other piece of information along with the actual event itself, to do this you’ll need a simple extension to the base class.

_Event.as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package events {
 
	import flash.events.Event;
 
	public class _Event extends Event {
 
		public var data:*;
 
		public function _Event(type:String="", someData:*=null, bubbles:Boolean=true, cancelable:Boolean=false)
		{
			super(type, bubbles, cancelable);
			this.data = someData;
		}
 
		override public function clone() : Event
		{
			return new _Event(type, data, bubbles, cancelable);
		}
	}
}

Stuff the data in the event when you fire it off and retrieve or modify it in your listeners. You should be creating a separate child class or each main category of events your application is defining. For instance if you were dealing with muting/unmuting your entire application you might create an AudioEvent class or if you were communicating with a server to gather user information you might create a UserEvent class and a ServerEvent class. In each of your child classes put your “public static const EVENT_TYPE:String = ‘eventType’;” declarations related to that particular type of event. Doing this forces you to think about how to best separate the different concerns influencing the behavior of your application.

If you want stricter compile-time type checking just add typed getter methods that wrap the data property to your child event classes.

To declare that your MXML component dispatches a certain custom event in your MXML file so you get compile-time code hinting:

<mx:Metadata>
     [Event(name="cancelled", type="events.FormEvent")]
</mx:Metadata>

To declare that your ActionScript class dispatches a certain custom event, in-between your package declaration and your class declaration:

[Event(name="createScheduleComplete", type="events.ScheduleEvent")]

That’s your basic custom event primer, hopefully straightforward enough to get you pointed in the right direction should you just be joining the Flash/Flex community. I hope to do a post about unleashing the power of events with Swiz in the near future, but if you have other cool uses for custom events or think I’m doing something terribly wrong, write it up and let me know in the comments!

Tagged : , ,

Leave a Reply