Event Class

In our Actionscript 2 games and engines we implement our event listeners a little differently to the way Adobe do. What follows is a brief explanation of how and why we do this, plus the Event class used within all our Actionscript 2 games.

Macromedia adopted two techniques for implementing event listeners. They are the ASBroadcaster class, used in Flash’s intrinsic classes, and EventBroadcaster, used in all their components. We dislike both these techniques for a number of reasons.

  • Both are mixins, with all the disadvantages that entails.
  • Both require the listening object to define functions with specific names in order to handle the events.
  • With ASBroadcaster, all events are broadcast to all listeners. There is no way for the listener to select only specific events to listen too.
  • With EventDispatcher, events must be specified by name as a String, which means there is no compile time checking that the event exists.

In all our code, events are created as properties of the class. For example

import BigRoom.Event; class SimpleButton { public var click:Event; public function SimpleButton() { click = new Event(); } public function onRelease():Void { click.notify( this ); } }

The notify call dispatches the event to all the listeners along with any parameters passed to the notify method. Listeners subscribe to the event via a call to the addListener method of the event, as in the following example

class ButtonListener { public function ButtonListener( btn:SimpleButton ) { btn.click.addlistener( this, buttonClick ); } public function buttonClick( obj:SimpleButton ):Void { // do something here… } }

No mixins, no Strings, no fixed method names, and listeners subscribe to receive specific events. The technique isn’t without its flaws, but we consider it far better than ASBroadcaster or EventDispatcher.

What about Actionscript 3?

In Actionscript 3, listening to events is implemented more consistently throughout the API, and static variables are used in preference to Strings. This is a vast improvement over the situation with Actionscript 2 and although we still prefer our technique we have decided to use the built-in event handling system in our Actionscript 3 code to be consistent with other peoples code. However, if you want it an Actionscript 3 version of this event class (with enhancements) is available on my blog.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply