User Guide
Using listeners to handle events 57
• To register a listener to a broadcaster, call the addEventListener() method from the
broadcaster. Use the following syntax:
componentInstance.addEventListener("eventName", listenerObjectORFunction);
• You can register multiple listeners to one component instance.
myButton.addEventListener("click", listener1);
myButton.addEventListener("click", listener2);
• You can register one listener to multiple component instances.
myButton.addEventListener("click", listener1);
myButton2.addEventListener("click", listener1);
• The handler function is passed an event object.
You can use the event object in the body of the function to retrieve information about the
event type, and the instance that broadcast the event. See “About the event object” on page 66.
Using listener objects
To use a listener object, you can either use the
this keyword to specify the current object as the
listener, use an object that already exists in your application, or create a new object.
• Use this in most situations.
It’s often easiest to use the current object (
this) as a listener, because its scope contains the
components that need to react when the event is broadcast.
• Use an existing object if it is convenient.
For example, in a Flash Form Application, you may want to use a form as a listener object if
that form contains the components that react to the event. Place the code on a frame of the
form’s Timeline.
• Use a new listener object if many components are broadcasting an event (for example, the
click event) and you want only certain listener objects to respond.
If you use the
this object, define a function with the same name as the event you want to handle;
the syntax is as follows:
function eventName(evtObj:Object){
// your code here
};
If you want to use a new listener object, you must create the object, define a property with the
same name as the events, and assign the property to a callback function that executes when the
event is broadcast, as follows:
var listenerObject:Object = new Object();
listenerObject.eventName = function(evtObj:Object){
// your code here
};
If you want to use an existing object, use the same syntax as a new listener object, without
creating the new object, as shown here:
existingObject.eventName = function(evtObj:Object){