User Guide
72 Handling Component Events
The following code illustrates the scoping of a function when passed to addEventListener()
in 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,
myButton, and a DataGrid component, myGrid.
Select both components on the Stage and press F8 to convert them into a new symbol named
Cart. In the Linkage properties for the Cart symbol, assign it the class Cart.
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.
*/
trace("this: " + this);
trace("myGrid: " + myGrid);
}
}
// register the myHandler function with myButton
// when the button is clicked, myHandler executes
function onLoad():Void{
myButton.addEventListener("click", myHandler);
}
}