O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Custom Events

Dispatching a new custom event in ActionScript is as simple as extending the EventDispatcher class, giving the new event a name, and invoking the EventDispatcher class's instance method dispatchEvent( ). To learn how to create custom events in a program, we'll study two examples: first, an event in a game, and then an event for a user interface widget.

Tip

To target an event dispatch at an instance of a class that already extends a class another, use the composition approach discussed in Chapter 9: implement the IEventDispatcher interface directly, and use EventDispatcher's services via composition rather than inheritance.

A Custom "gameOver" Event

Suppose we're creating a general framework for video game development. The framework includes the following two classes: Game, which handles the basic needs of any video game; and Console, which represents a launchpad from which to start new games. The Console class instantiates a Game object whenever a new game is started. Each Game class instance created by the Console class is the target of a custom "gameOver" event, which is dispatched when a game ends.

In order to allow Game objects to act as event targets, the Game class extends EventDispatcher, as follows:

package {
  import flash.events.*;

  public class Game extends EventDispatcher {
  }
}

The Game class also defines a constant, Game.GAME_OVER, whose value is the name of the custom event: gameOver. By convention, event constants are written with all capital letters, and words ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required