User Guide
Using listeners to handle events 67
8. In the Actions panel, enter the following code:
var myButton:mx.controls.Button;
var myText:mx.controls.TextInput;
function click(evt){
myText.text = evt.target;
}
myButton.addEventListener("click", this);
The target property of the event object, evt, is a reference to the instance broadcasting
the event. This code displays the value of the
target property in the TextInput
component.
To register a listener object in a class (AS) file:
1. Open the file TipCalculator.fla from the location specified in “Working with
Components” on page 49.
2. Open the file TipCalculator.as from the location specified in “Working with Components”
on page 49.
3. In the FLA file, select form1 and view the class name, TipCalculator, in the
Property inspector.
This is the link between the form and the class file. All the code for this application is in
the TipCalculator.as file. The form assumes the properties and behaviors defined by the
class assigned to it.
4. In the AS file, scroll to line 25, public function onLoad():Void.
The
onLoad() function executes when the form loads into Flash Player. In the body of the
function, the
subtotal TextInput instance and the three RadioButton instances,
percentRadio15, percentRadio18, and percentRadio20, call the
addEventListener() method to register a listener with an event.
5. Look at line 27, subtotal.addEventListener("change", this).
When you call
addEventListener(), you must pass it two parameters. The first is a
string indicating the name of the event that is broadcast—in this case,
"change". The
second is a reference to either an object or a function that handles the event. In this case,
the parameter is the keyword
this, which refers to an instance of the class file (an object).
Flash then looks on the object for a function with the name of the event.
6. Look at line 63, public function change(event:Object):Void.
This is the function that executes when the subtotal TextInput instance changes.
7. Select TipCalculator.fla and select Control > Test Movie to test the file.