User Guide
Example: Alarm Clock 369
Other code can register to be notified of the AlarmClock class’s alarm event by calling the
addEventListener() method that AlarmClock inherits from EventDispatcher. When an
AlarmClock instance is ready to notify other code that its
alarm event has been raised, it does
so by calling the
dispatchEvent() method, which is also inherited from EventDispatcher.
var alarm:AlarmEvent = new AlarmEvent(this.alarmMessage);
this.dispatchEvent(alarm);
These lines of code are taken from the AlarmClock class’s onAlarm() method (shown in its
entirety previously). The AlarmClock instance’s
dispatchEvent() method is called, which in
turn notifies all the registered listeners that the AlarmClock instance’s
alarm event has been
triggered. The parameter that is passed to
dispatchEvent() is the event object that will be
passed along to the listener methods. In this case, it is an instance of the AlarmEvent class, an
Event subclass created specifically for this example.
Providing a custom alarm event
All event listeners receive an event object parameter with information about the particular
event being triggered. In many cases, the event object is an instance of the Event class.
However, in some cases it is useful to provide additional information to event listeners. As
described earlier in the chapter, a common way to accomplish this is to define a new class, a
subclass of the Event class, and use an instance of that class as the event object. In this
example, an AlarmEvent instance is used as the event object when the AlarmClock class’s
alarm event is dispatched. The AlarmEvent class, shown here, provides additional
information about the
alarm event, specifically the alarm message:
import flash.events.Event;
/**
* This custom Event class adds a message property to a basic Event.
*/
public class AlarmEvent extends Event
{
/**
* The name of the new AlarmEvent type.
*/
public static const ALARM:String = "alarm";
/**
* A text message that can be passed to an event handler
* with this event object.
*/
public var message:String;
/**
* Constructor.