User Guide

170 Chapter 5: Handling Events
The listener/broadcaster model for events, unlike event handler methods, lets you have multiple
pieces of code listen to the same event without conflict. Event models that do not use the listener/
broadcaster model, such as
XML.onLoad, can be problematic when various pieces of code are
listening to the same event; the different pieces of code have conflicts over control of that single
XML.onLoad callback function reference. With the listener/broadcaster model, you can easily
add listeners to the same event without worrying about code bottlenecks.
The following ActionScript classes can broadcast events: “Key class”, “Mouse class”,
“MovieClipLoader class”, “Selection class”, “Stage class”, and “TextField class”. To see which
listeners are available for a class, see each class entry.
Event listener model
The event model for event listeners is similar to the model for event handlers (see “Using event
handler methods” on page 167), with two main differences:
You assign the event handler to the listener object, not the object that broadcasts the event.
You call a special method of the broadcaster object, addListener(), which registers the
listener object to receive its events.
The following code outlines the event listener model:
var listenerObject.eventName = function(){
// your code here
};
broadcasterObject.addListener(listenerObject);
The code starts with an object, listenerObject, with a property eventName. Your listener
object can be any object, such as an existing object, movie clip, or button instance on the Stage, or
it can be an instance of any ActionScript class. For example, a custom movie clip could
implement the listener methods for Stage listeners. You could even have one object that listens to
several types of listeners.
The
eventName property is an event that occurs on broadcasterObject, which then broadcasts
the event to
listenerObject. You can register multiple listeners to one event broadcaster.
You assign a function to the event listener that responds to the event in some way.
Last, you call the
addListener() method on the broadcaster object, passing it the name of the
listener object.
To unregister a listener object from receiving events, you call the
removeListener() method of
the broadcaster object, passing it the name of the listener object.
broadcasterObject.removeListener(listenerObject);
Event listener example
The following example shows how to use the
onSetFocus event listener in the Selection class to
create a simple focus manager for a group of input text fields. In this case, the border of the text
field that receives keyboard focus is enabled (appears), and the border of the text field that does
not have focus is disabled.