User Guide
368 Handling Events
This method does several things, including storing the alarm message and creating a Date
object (
alarmTime) representing the actual moment in time when the alarm is to go off. Of
most relevance to the current discussion, in the final several lines of the method, the
alarmTimer variable’s timer is set and activated. First, its reset() method is called, stopping
the timer and resetting it in case it is already running. Next, the current time (represented by
the
now variable) is subtracted from the alarmTime variable’s value to determine how many
milliseconds need to pass before the alarm goes off. The Timer class doesn’t trigger its
timer
event at an absolute time, so it is this relative time difference that is assigned to the
delay
property of
alarmTimer. Finally, the start() method is called to actually start the timer.
Once the specified amount of time has passed,
alarmTimer dispatches the timer event.
Because the AlarmClock class registered its
onAlarm() method as a listener for that event,
when the
timer event happens, onAlarm() is called.
/**
* Called when the timer event is dispatched.
*/
public function onAlarm(event:TimerEvent):void
{
trace("Alarm!");
var alarm:AlarmEvent = new AlarmEvent(this.alarmMessage);
this.dispatchEvent(alarm);
}
A method that is registered as an event listener must be defined with the appropriate signature
(that is, the set of parameters and return type of the method). To be a listener for the Timer
class’s
timer event, a method must define one parameter whose data type is TimerEvent
(flash.events.TimerEvent), a subclass of the Event class. When the Timer instance calls its
event listeners, it passes a TimerEvent instance as the event object.
Notifying others of the alarm
Like the Timer class, the AlarmClock class provides an event that allows other code to receive
notifications when the alarm goes off. For a class to use the event handling framework built
into ActionScript, that class must implement the flash.events.IEventDispatcher interface.
Most commonly, this is done by extending the flash.events.EventDispatcher class, which
provides a standard implementation of IEventDispatcher (or by extending one of
EventDispatcher’s subclasses). As described previously, the AlarmClock class extends the
SimpleClock class, which in turn extends the mx.core.UIComponent class, which (through a
chain of inheritance) extends the EventDispatcher class. All of this means that the
AlarmClock class already has built-in functionality to provide its own events.