Screenwriter, Choreographer, Game Developer

Events in Actionscript 2

Posted on

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 )
    { 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.

Share this post or a comment online -

Also in the collection Actionscript