User Guide

60 Chapter 4: Handling Component Events
function handleEvent(evt){
// check if the event was a click
if (evt.type == "click"){
// do something if the event was click
} else if (evt.type == "change"){
// do something else if the event was change
}
};
// register the listener object to
// two different component instances
// because the function is defined on
// "this" object, the listener is this.
instance.addEventListener("click", this);
instance2.addEventListener("change", this);
Using listener functions
Unlike the
handleEvent syntax, several listener functions can handle different events. So instead
of having the
if and else if checks in myHandler, you can just define myChangeHandler for
the
change event and myScrollHandler for the scroll event and register them, as shown here:
myList.addEventListener("change", myChangeHandler);
myList.addEventListener("scroll", myScrollHandler);
To use a listener function, you must first define a function:
function myFunction:Function(evtObj:Object){
// your code here
}
Tip: The
evtObj parameter is an object that is automatically generated when an event is triggered and
passed to the function. The event object has properties that contain information about the event. For
details, see “About the event object” on page 66.
Then you call the addEventListener() method from the component instance that broadcasts
the event. The
addEventListener() method takes two parameters: a string indicating the name
of the event and a reference to the function.
componentInstance.addEventListener("eventName", myFunction);
You can call addEventListener() from any component instance; it is mixed in to every
component from the EventDispatcher class. For more information, see
EventDispatcher.addEventListener() on page 416.
For information about the events a component broadcasts, see each components entry in
Chapter 6, “Components Dictionary,” on page 91.
To register a listener object in a Flash (FLA) file:
1.
In Flash, select File > New and create a new Flash document.
2.
Drag a List component to the Stage from the Components panel.
3.
In the Property inspector, enter the instance name myList.