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 and the Event Flow

ActionScript's hierarchical event system applies to all event-dispatches targeted display objects—even those event dispatches instigated manually by the programmer. When a custom event dispatch targets an object in a display hierarchy, the ancestors of that target object are notified of the event.

The generalized code shown in Example 21-5 demonstrates how, just like built-in events, custom events propagate through the event flow. In the example, a test class, CustomEventDemo instructs ActionScript to dispatch a custom event targeted at a Sprite object on the display list.

Example 21-5. A custom event dispatched through the event flow

package {
  import flash.display.*;
  import flash.events.*;
  import flash.text.*;

  public class CustomEventDemo extends Sprite {
    public static const SOME_EVENT:String = "SOME_EVENT";

    public function CustomEventDemo () {
      var sprite:Sprite = new Sprite();
      addChild(sprite);

      // Register someEventListener() with the Stage instance for
      // CustomEventDemo.SOME_EVENT notification.
      stage.addEventListener(CustomEventDemo.SOME_EVENT, someEventListener);

      // Dispatch a CustomEventDemo.SOME_EVENT event to an object on
      // the display list. Set the Event constructor's second parameter
      // to true so the event bubbles.
      sprite.dispatchEvent(new Event(CustomEventDemo.SOME_EVENT, true));
    }

    private function someEventListener (e:Event):void {
      trace("SOME_EVENT occurred.");
    }
  }
}

In response to the dispatchEvent( ) invocation in Example 21-5, ActionScript ...

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