User Guide

Using listeners to handle events 59
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 43.
2.
Open the file TipCalculator.as from the location specified in Working with Components
on page 43.
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 file
TipCalculator.as. 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 the TipCalculator.fla and select Control > Test Movie to test the file.
Using the handleEvent callback function
You can also use listener objects that support a
handleEvent function. Regardless of the name of
the event that is broadcast, the listener object’s
handleEvent method is called. You must use an
if else or a switch statement to handle multiple events. For example, the following code uses
an
if else statement to handle the click and change events:
// define the handleEvent function
// pass it evt as the event object parameter