User Guide

Using listeners to handle events 71
7. Select Control > Test Movie; then select an item in the list and scroll the list to see the
results in the Output panel.
About scope in listeners
Scope refers to the object within which a function executes. Any variable references within that
function are recognized as properties of that object. You can use the Delegate class to specify
the scope of a listener. For more information, see “Delegating events” on page 73.
As discussed earlier, you register a listener with a component instance by calling
addEventListener(). This method takes two parameters: a string indicating the name of the
event, and a reference to either an object or a function. The following table lists the scope of
each parameter type:
If you pass
addEventListener() an object, the callback function assigned to that object (or
the function defined on that object) is invoked in the scope of the object. This means that the
keyword
this, when used inside the callback function, refers to the listener object, as follows:
var lo:Object = new Object();
lo.click = function(evt){
// this refers to the object lo
trace(this);
}
myButton.addEventListener("click", lo);
However, if you pass addEventListener() a function, the function is invoked in the scope of
the component instance that calls
addEventListener(). This means that the keyword this,
when used inside the function, refers to the broadcasting component instance. This causes a
problem if youre defining the function in a class file. You cannot access the properties and
methods of the class file with the expected paths because
this doesnt point to an instance of
the class. To work around this problem, use the Delegate class to delegate a function to the
correct scope. See “Delegating events” on page 73.
CAUTION
In a listener function, the keyword this refers to the component instance that calls
addEventListener(), not to the timeline or the class where the function is defined.
However, you can use the Delegate class to delegate the listener function to a
different scope. See “Delegating events” on page 73. To see an example of function
scoping, see the next section.
Listener type Scope
Object Listener object.
Function Component instance broadcasting the event.