AS Reference  :  Notes Index  :  Resources  :  About/Contact  :  Downloads

Using the EventDispatcher Class

Get the latest Flash player here

In Actionscript 2, one of the best ways to communicate between classes is with EventDispatcher. On this page, I'll show an example of a very simple application that uses two classes, Sender and Receiver, which communicate via EventDispatcher (which is built into Flash 7 and 8, but requires an import statement to use). These two classes can be used as a starting point for any application that requires communication via EventDispatcher.

The class that dispatches events

Any class which must dispatch (broadcast) events should be given a structure like this:

/**
 *  @class        Sender
 *  @author       Helen Triolo
 *  @description  Example of code needed to enable a class to broadcast events using
 *                  EventDispatcher. All the code in this class needs to be included 
 *                  in a dispatching class, except the setInterval line (which is just
 *                  included here to force an actual event broadcast). The name of the
 *                  event ("eventFired") should be changed to something appropriate 
 *                  (eg, shooterFired, or handleDragged), and any number of variables
 *                  may be passed (not just the one, elapsedTime, shown here), of any 
 *                  legitimate dataType.
 *  @language     Actionscript 2.0
 *
*/

import mx.events.EventDispatcher;

class Sender {
   
   // these three lines are needed to use EventDispatcher
   public var addEventListener:Function;
   public var removeEventListener:Function;
   public var dispatchEvent:Function;   
   

   public function Sender() {
      // this line must be in the constructor of the class
      EventDispatcher.initialize(this);
      
      // dispatch an event once per second
      setInterval(this, "sendEvent", 1000);
   }

   private function sendEvent():Void {
      dispatchEvent({target:this, type:"eventFired", elapsedTime:getTimer()});         
   }
}   
in which
  1. the EventDispatcher code is imported,
  2. the three required function properties are declared,
  3. EventDispatcher is initialized (usually in the class constructor),
  4. and
  5. whatever events are needed are broadcast using the dispatchEvent method.

The properties in the object sent by dispatchEvent include:

The only line that is specific to this example is the setInterval line, which is included to actually cause an event to be dispatched -- in this case, once every second.

The class that responds to events

The Receiver class looks like this:

/**
 *  @class         Receiver
 *  @author        Helen Triolo
 *  @description   Example of code needed to enable a class to listen for 
 *                    events broadcast by another class and respond to them
 *  @language      Actionscript 2.0
 *
*/
import mx.utils.Delegate;

class Receiver {
   
   private var timeline:MovieClip;
   
   public function Receiver($timeline:MovieClip) {
      timeline = $timeline;
      var sender:Sender = new Sender();
      sender.addEventListener("eventFired", Delegate.create(this, onEventFired));
   }

   public function onEventFired(o:Object):Void {
      timeline.msg.text = "You've been here for " + Math.round(o.elapsedTime/1000) + " seconds";
   }
}   
The only lines that need to be included in a receiving class are
  1. import.mx.utils.Delegate: because you'll need it to define the scope of the responding function
  2. a line to create an instance of the broadcasting class (var sender:Sender = new Sender() in this case)
  3. one line per event to be listened for, to specify which function will deal with the event (in our case, a line to say that the function onEventFired will be called whenever the sender broadcasts an "eventFired" event. Those are very generic names and should be replaced by ones which more appropriately describe the event and responder functions -- itemDragged and onItemDragged, respectively, for example).

In this case, the responding function simply collects the one variable passed back, elapsedTime, and displays it with a message in the msg textfield. Notice that variables passed via dispatchEvent are available as properties of the one parameter, a variable of type Object, of the responding function. This variable is always available and can be named with any name you like -- I used "o" for simplicity. So o contains all of the information passed back by the dispatching class, and I can pull whatever variables were named in the dispatchEvent call as properties, eg, o.elapsedTime

Using these classes with a fla

Once the Receiver.as file and Sender.as file have been created, the only thing the fla needs is a call to instantiate the Receiver (which creates its own Sender instance), and whatever graphic content is required to support the classes -- this case, a dynamic textfield named msg. An instance of Receiver is created, and a reference to the current timeline passed to it, with this line in frame 1 of the fla:

var rec:Receiver = new Receiver(this);

You can download the files used in this example at the right with the "free download" link. To see an example of EventDispatcher used in a simple game application, see the class-based version of the Dart Shooter Game.

Intro
Flash: What & How
Example Sites
Create
Draw, Edit Shapes
Gradients
More Drawing Tips
Import
A Sample
Animate
Frames, Keyframes
Motion Tweens
More Motion Tweens
Shape Tweens
Masks
Control
Stop/Replay
Movieclips Intro
Movieclip Reference
Site Structure 1
Slideshow Movieclip
Contact Form
Scroll Resume
Preloader
Site Structure 2
Publish
Display Options
Player Detection
Optimize
AS 2.0 Basics
Intro to Syntax
Playhead Commands
Playhead Cmds 2
Coded Tween
onEnterFrame
Intro to Classes
Declare/Assign
Comments, Trace
Simple Data Types
Arrays & Objects
Code Blocks
Operators
Beyond Buttons
Code Structure
Toggle Controls
Group of Buttons
Drag and Hit
Distort Magnifier
Scroll Text
Bee Game
Dart Shooter
Sound Control
Easing Slider
Easing Slider 2
Components Intro
Timers & Delays
Dynamic Content
Intro
Drawing API
Create Text
Attach Movieclips
Easing Slider 3
Easing Slider 4
Load jpg/swf
Sliding Viewer
Preload swf
XML
Easing Slider 5
Server Comm
LoadVars (w/ PHP)
AS - PHP Lookup
Text File
Database 1:LoadVars
Database 2:Remoting
Read from directory
AS 2.0 Classes
Intro
Math
Key
Date
Color
EventDispatcher
New Samples
Pie Chart
Event-model Emailer
Tween Sequence
Fuse Sequence
SVG in Flash
Bitmap Topo
SWF as Data Holder
Two-level Menu
Yahoo! Flash Maps
Class-based Game
ASTB Samples
Disclaimer
3D Outlines
Bounce Collide
Address Book
Save Drawings
Home  :  Notes Index  :  Resources  :  About/Contact  :  Downloads