Traditional, non-event-driven applications are susceptible to problems that give rise to the motivation for events and a unified event model. There are two primary problems with the traditional approach:
Earlier versions of ActionScript use many different ways of responding to occurrences within the application. However, ActionScript 3.0 has one unified event model used across the board. At the core of this event model is the flash.events package of classesnamely the Event class and the Eventdispatcher class. The Eventdispatcher class provides all the functionality to allow objects to register for event notifications. When an object registers with an event dispatcher for notifications for a particular event, the event dispatcher adds that object to a queue. When the event occurs, the event dispatcher notifies all the objects in the queue. The objects in the queue are called listeners, and in ActionScript 3.0 all listeners are functions/methods. When a listener is notified, it gets called and passed a parameter of type Event (or a subtype specific to the type of event). The event parameter provides the context for the event, including the type of event and the object that dispatched the event. This arrangement allows for the event dispatcher and the listener to know virtually nothing about one another at compile time, but at runtime, the listener can obtain a reference back to the dispatcher using the event parameter. This powerful design means that the dispatchers and listeners are loosely coupled. It also means that many listeners can register for notifications when an event occurs for just one dispatcher. Figure 13.1 illustrates this concept. Figure 13.1. An event is handled.
In ActionScript 3.0, the event model is closely related to a well-known design pattern called the Observer pattern. Although the Observer pattern is an important pattern, we don't discuss it in any detail in this book because the built-in event model in ActionScript 3.0 already solves all the design patterns the Observer pattern is intended to solve. |