Events in Actionscript 2

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. I 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.

So a couple of years ago I devised a new option. This technique uses a single Event class. You set-up events on an object by creating a public property that is an Event. Other objects may then listen to this event and the object dispatches the event when it wishes. 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 I consider it far better than ASBroadcaster or EventDispatcher.

Download source code Download the Event class.

6 thoughts on “Events in Actionscript 2

  1. Yeah this is a really good method, I wish we could have gone with something a little more robust like this with AS3. I love the way multicast delegates work in C# even though the consistency has improved and more people are using consts for the event types.

    The AS3 version of this technique would be slightly less verbose because of method enclosure but it’s still a refreshing look at event dispatching, thanks.

  2. Only sorry I didn’t share it sooner. I came up with the idea before I created this blog so sharing it wasn’t so easy then. Didn’t think about it later until writing documentation for flashgamecode.net.

  3. This has saved me a world of grief in developing my platformer framework. Thank you so much. My hero.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>