ActionScript & Flash

Custom events in ActionScript 3

A custom event lets a game object report something meaningful without knowing which object will respond. A score counter can listen for an enemy defeated event; the enemy does not need a reference to the score display.

Extend Event when you need a payload. Use a constant for the event type, pass the type to the base constructor, and implement clone so redispatched events preserve their data. Prefer a small, explicit payload over handing a listener the entire mutable game world.

Add listeners when an object becomes active and remove them during teardown. A screen that remains subscribed after it closes can process events twice or keep otherwise unused objects in memory.

Try the idea

import flash.events.Event;

public class ScoreEvent extends Event {
  public static const ADDED:String = "scoreAdded";
  public var points:int;
  public function ScoreEvent(points:int) {
    super(ADDED); this.points = points;
  }
  override public function clone():Event {
    return new ScoreEvent(points);
  }
}