User Guide
Delegating events 63
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);
}
}
Delegating events
You can import the Delegate class into your scripts or classes to delegate events to specific scopes
and functions. Use the following syntax:
import mx.utils.Delegate;
compInstance.addEventListener("eventName", Delegate.create(scopeObject,
function));
The scopeObject parameter specifies the scope in which the specified function parameter is
called.
There are two common uses for calling
Delegate.create():
• To dispatch the same event to two different functions.
See the next section.
• To call functions within the scope of the containing class.
When you pass a function as a parameter to
addEventListener(), the function is invoked in
the scope of the broadcaster component instance, not the object in which it is declared. See
“Delegating the scope of a function” on page 65.
Delegating events to functions
Calling
Delegate.create() is useful if you have two components that broadcast events of the
same name. For example, if you have a check box and a button, you would have to use the
switch
statement on the information you get from the
eventObject.target property in order to
determine which component is broadcasting the
click event.
To use the following code, place a check box named
myCheckBox_chb and a button named
myButton_btn on the Stage. Select both instances and press F8 to create a new symbol. Click
Advanced, Export for ActionScript, and enter the AS 2.0 class name Cart. You can give the new
symbol any instance name you want in the Property inspector. The symbol is now an instance of
the Cart class.
import mx.utils.Delegate;
import mx.controls.Button;
import mx.controls.CheckBox;
class Cart {
var myCheckBox_chb:CheckBox;