As discussed earlier, you register a listener with a component instance by calling
addEventListener()
event, and a reference to either an object or a function. The following table lists the scope of each
parameter type:
Listener type
Object
Function
If you pass
addEventListener()
function defined on that object) is invoked in the scope of the object. This means that the
keyword
, when used inside the callback function, refers to the listener object, as follows:
this
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
component instance that calls
used inside the function, refers to the broadcasting component instance. This causes a problem if
you're defining the function in a class file. You cannot access the properties and methods of the
class file with the expected paths because
around this problem, use the Delegate class to delegate a function to the correct scope. See
"Delegating events" on page
The following code illustrates the scoping of a function when passed to
a class file. To use this code, copy it into an ActionScript (AS) file named Cart.as. Create a Flash
(FLA) file with a Button component,
both components on the Stage and press F8 to convert them into a new symbol named
the Linkage properties for the Cart symbol, assign it the class
class Cart extends MovieClip {
var myButton:mx.controls.Button;
var myGrid:mx.controls.DataGrid;
function myHandler(eventObj:Object){
// Use the eventObj parameter
// to capture the event type.
if (eventObj.type == "click"){
/* Send the value of this to the Output panel.
Because myHandler is a function that is not defined
on a listener object, this is a reference to the
component instance to which myHandler is registered
(myButton). Also, since this doesn't reference an
instance of the Cart class, myGrid is undefined.
*/
62
Chapter 4: Handling Component Events
. This method takes two parameters: a string indicating the name of the
an object, the callback function assigned to that object (or the
addEventListener()
addEventListener()
this
63.
myButton
Scope
Listener object
Component instance broadcasting the event
a function, the function is invoked in the scope of the
. This means that the keyword
doesn't point to an instance of the class. To work
, and a DataGrid component,
Cart
this
addEventListener()
. Select
myGrid
Cart
.
, when
in
. In
Need help?
Do you have a question about the FLASH MX 2004-USING COMPONENTS and is the answer not in the manual?
Questions and answers