« | »

Events in Actionscript 2

14th August 2007

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.

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.

Tags: , ,  

6 Comments add your own

Leave a Comment comment policy

required

required, hidden

XHTML: you can use these tags - <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe to the comments via RSS Feed