Tutorials Books Videos Forums

-- online Change the theme! Search!
Rambo ftw!

Customize Theme


Color

Background


Done

Using EventDispatcher

by Jesse Marangoni aka TheCanadian   | filed under Flash and ActionScript

This is an archived tutorial from the kirupa.com legacy collection. It covers software that may no longer be available, but it is kept online because the ideas still hold up.

EventDispatcher is a class which provides a means of dispatching events. After you’ve recovered from that bombshell of an introduction sentence, let’s get more in depth. EventDispatcher, like AsBroadcaster broadcasts an event to a set of listeners which then receive that event and call the function associated with it. If you have ever used the Key class, you’ll be familiar with how you have to add a listener to Key then set up events such as onKeyDown. These events are in fact handled by AsBroadcaster but EventDispatcher performs much the same function. If you ever used components and such functions as addEventListener, you will have definitely used this class before (even if not knowing it) since EventDispatcher handles all v2 component events. This tutorial will attempt to teach you the concepts behind it and how to use it in your projects.

AsBroadcaster vs. EventDispatcher

You can’t really place these two classes in direct comparison since each has its strengths and weaknesses. AsBroadcaster has one single collection of listeners which receive every event broadcast. EventDispatcher has a group of listeners for each event it broadcasts. Senocular paints a nice picture:

[ Comparison of EventDispatcher and AsBroadcaster ]

It all boils down to which class is best for each situation. EventDispatcher is good when you need different listeners for different events. If you used AsBroadcaster in this situation you would find yourself with a bunch of listeners receiving events that they never use. But if you need multiple listeners listening to the same events it would be quite cumbersome to be adding those listeners to listen for each event. This is where AsBroadcaster shines.

For more info on AsBroadcaster and listeners, see senoculars tutorial: //www.kirupa.com/developer/actionscript/asbroadcaster.htm

One last thing to note about EventDispatcher is its ability to have functions as a part of an event collection. With AsBroadcaster this isn’t possible given that each listener listens to every event but, since EventDispatcher is event oriented, you can have functions which are called when the event they are signed up to is broadcast.

How It Works

Before we get to using it, you should have a brief understanding of how a broadcasting object is initialized. In its most basic sense, EventDispatcher is simply a container for methods which are given to a broadcasting instance when it is initialized. If we take a peek at its static initialize method we can see how objects are set up to begin broadcasting:

static function initialize(object:Object):Void {
  if (_fEventDispatcher == undefined) {
  _fEventDispatcher = new EventDispatcher();
  }
  object.addEventListener = _fEventDispatcher.addEventListener;
  object.removeEventListener = _fEventDispatcher.removeEventListener;
  object.dispatchEvent = _fEventDispatcher.dispatchEvent;
  object.dispatchQueue = _fEventDispatcher.dispatchQueue;
}

Calling that method just gives four methods of an instance of EventDispatcher to the object passed to the function. The object can now call these methods as if they were its own – in its own scope. When broadcasting an event, the broadcaster will loop through all listeners of that event and call the function associated with it.

We have barely scratched the surface of how this function works. Onwards to the next section!

In the previous section, I provided a brief introduction of EventDispatcher. In this page, let's go through a code example to make sense of how this all should work.

Getting It to Work

Example time with a clever metaphor:

//Import the class.
import mx.events.EventDispatcher;
//Create a generic object to serve as our broadcaster.
this.radioStation = new Object();
//Initialize the object, remember that this gives the methods of EventDispatcher to radioStation.
EventDispatcher.initialize(this.radioStation);
//Let's create our music lovers (rockListener and classicalListener), add them as listeners to the radioStation and give them
//actions for when their favourite music is playing.
this.rockListener = new Object();
this.radioStation.addEventListener("rockMusic", this.rockListener);
this.rockListener.rockMusic = function(eventObject:Object):Void {
  trace("I love " + eventObject.type + ". The song " + eventObject.title + " by " + eventObject.artist + " is awesome!\n");
};
this.classicalListener = new Object();
this.radioStation.addEventListener("classicalMusic", this.classicalListener);
this.classicalListener.classicalMusic = function(eventObject:Object):Void {
  trace("I admire " + eventObject.type + ". The song " + eventObject.title + " by " + eventObject.artist + " is magnificent!\n");
};
//Now that we have a fan base, we can fire up the tunes. You should notice that each listener only responds to the type of music
//it is set up to listen to.
//rockListener picks up this event and calls its function relating to the event but classicalListener doesn't listen.
this.radioStation.dispatchEvent({type:"rockMusic", title:"Rockin' In The Free World", artist:"Neil Young"});
//rockListener also recives this event and calls the function.
this.radioStation.dispatchEvent({type:"rockMusic", title:"Born To Be Wild", artist:"Steppenwolf"});
//No listener recives this event since none are subscribed to listen for it.
this.radioStation.dispatchEvent({type:"advertisement", title:"Buy Coke!!!", artist:"Coca-Cola"});
//Finially classical gets to listen to some beehtoven. You'll notice that rockListener tunes out for this.
this.radioStation.dispatchEvent({type:"classicalMusic", title:"Symphony 5", artist:"Ludwig van Beethoven"});

As you can see it’s fairly simple to use. Initialize a broadcaster, add event listeners and dispatch events. The key to dispatching an event lies in the object you pass as the parameter. In this object you must include the type property; this is the event that gets dispatched. You should also include a target property but the EventDispatcher will specify the broadcasting object as the target property for you if you don’t include a custom one. You can include as many properties as you want in this object which will get passed to the function called when the event is dispatched.

As said earlier, you can also add functions as listeners to an event as shown in this simple example:

import mx.events.EventDispatcher;
this.broadcaster = new Object();
EventDispatcher.initialize(this.broadcaster);
this.listener = function(eventObject:Object):Void {
  trace(eventObject.type + " broadcast to all listeners of the event.");
};
this.broadcaster.addEventListener("genericEvent", this.listener);
this.broadcaster.dispatchEvent({type:"genericEvent"});

It works in much the same manner as with listening objects except it bypasses the need of an event named method of a listener. But you must note that the function is run in the scope of the broadcasting object (not the scope it was defined in). You can fix this using a class called Delegate which will be the subject of another tutorial.

You can also handle events using an appropriately named function called handleEvent as a property of a listener. This is a function which gets called as a method of any listener subscribed to the event broadcast.

import mx.events.EventDispatcher;
this.broadcaster = new Object();
EventDispatcher.initialize(this.broadcaster);
this.listener = new Object();
this.listener.handleEvent = function():Void {
  trace("handleEvent called");
};
this.broadcaster.addEventListener("genericEvent", this.listener);
this.broadcaster.addEventListener("otherGenericEvent", this.listener);
this.broadcaster.dispatchEvent({type:"genericEvent"});
this.broadcaster.dispatchEvent({type:"otherGenericEvent"});
//handleEvent called will appear in the output box twice

The example points out that as long as the listener is listening to an event that is broadcast, its handleEvent function will be called.

To close of this section you should know that you can’t have events named move, draw or load since they are reserved by the v2 component architecture.

There is more in the next section.

In the previous section, we went through a pretty detailed example of how EventDispatcher is used. Let's go through a smaller example on this page with more detailed code explanations.

EventDispatcher and Classes

Using the EventDispatcher in classes isn’t too different but there are a few tricks which can be helpful. And besides, another example never hurt anyone. We’ll dissect a class line for line:

import mx.events.EventDispatcher;
class Interval extends Object {
  private static var EventDispatcherDependancy = EventDispatcher.initialize(Interval.prototype);
  public var addEventListener:Function;
  public var removeEventListener:Function;
  public var dispatchEvent:Function;
  private var __timerInt:Number;
  private var __count:Number;
  public function Interval(time:Number) {
  this.__count = 0;
  this.__timerInt = setInterval(this, "increment", time);
  }
  private function increment():Void {
  this.dispatchEvent({type:"interval", num:__count});
  this.__count++;
  }
}

Code Explanation


import mx.events.EventDispatcher;

Import the EventDispatcher class.


class Interval extends Object {
Define a class called Interval for all of our timing needs.


private static var EventDispatcherDependancy = EventDispatcher.initialize(Interval.prototype);

Here’s where we start off with EventDispatcher in our class. In the previous examples we initialized each broadcaster individually. We could do this here and initialize each instance as a broadcaster in the class constructor. But this is the 21st century – an age of fast cars, television and class prototypes. By giving the EventDispatcher methods to the class prototype, we eliminate the need for each instance to have its own method (which will take up more memory).


public var addEventListener:Function;
public var removeEventListener:Function;
public var dispatchEvent:Function;

These are the methods that come from the EventDispatcher initialization. We must declare them as members of our class or the compiler will give us an error claiming that there is no such property.


private var __timerInt:Number;
private var __count:Number;

Just some private variables for our class, this has nothing to do with EventDispatcher


public function Interval(time:Number) {

Class constructor.


this.__count = 0;

Start the count of at 0.


this.__timerInt = setInterval(this, "increment", time);

Set the gears in motion, we call the increment method of the class every number of milliseconds as passed to the constructor.


private function increment():Void {

Private method.


this.__count++;

Increment the count property.


this.dispatchEvent({type:"interval", count:__count});

And this is where the magic happens. You’ll see that the object passed to the dispatchEvent method contains the mandatory property type as well as a custom count property which stores the amount of times the event has been dispatched.

And an example of the class in use:

this.intTest = new Interval(1000);
this.objListener = new Object();
this.objListener.interval = function(objEvent:Object) {
  trace("Interval dispatched, total intervals: " + objEvent.count + ".\n");
};
this.intTest.addEventListener("interval", this.objListener);

Conclusion

I hope this gives you a better understanding of how EventDispatcher works and how to implement it in your own movies. If you have any questions or suggestions for improvement, feel free to comment on the forums where a lot of people will be happy to help.

Good Luck!

Jesse Marangoni

TheCanadian

Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence, ads, and algorithm-driven doodads. A huge thank you to all of you who buy kirupa's books, became a paid subscriber, watch the videos, and/or interact on the forums.

Your support keeps this site going! 😇

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!

SUBSCRIBE NOW

Creating engaging and entertaining content for designers and developers since 1998.

Follow:

Popular

Loose Ends

:: Copyright KIRUPA 2026 //--