User Guide
76 Handling Component Events
Delegating the scope of a function
The addEventListener() method requires two parameters: the name of an event and a
reference to a listener. The listener can either be an object or a function. If you pass an object,
the callback function assigned to the object is invoked in the scope of the object. However, if
you pass a function, the function is invoked in the scope of the component instance that calls
addEventListener(). (For more information, see “About scope in listeners” on page 71.)
Because the function is invoked in the scope of the broadcaster instance, the keyword
this in
the body of the function points to the broadcaster instance, not to the class that contains the
function. Therefore, you cannot access the properties and methods of the class that contains
the function. Use the Delegate class to delegate the scope of a function to the containing class
so that you can access the properties and methods of the containing class.
The following example uses the same approach as the previous section with a variation of the
Cart.as class file:
import mx.controls.Button;
import mx.controls.CheckBox;
class Cart {
var myCheckBox_chb:CheckBox;
var myButton_btn:Button;
// define a variable to access
// from the chb_onClick function
var i:Number = 10
function onLoad() {
myCheckBox_chb.addEventListener("click", chb_onClick);
}
function chb_onClick(eventObj:Object) {
// You would expect to be able to access
// the i variable and output 10.
// However, this sends undefined
// to the Output panel because
// the function isn't scoped to
// the Cart instance where i is defined.
trace(i);
}
}