User Guide

166 Chapter 6: Components Dictionary
The first usage example uses an on() handler and must be attached directly to a CheckBox
instance. The keyword
this, used inside an on() handler attached to a component, refers to the
component instance. For example, the following code, attached to the check box
myCheckBox,
sends “_level0.myCheckBox” to the Output panel:
on(click){
trace(this);
}
The second usage example uses a dispatcher/listener event model. A component instance
(
checkBoxInstance) dispatches an event (in this case, click), and the event is handled by a
function, also called a handler, on a listener object (
listenerObject) that you create. You define
a method with the same name as the event on the listener object; the method is called when the
event is triggered. When the event is triggered, it automatically passes an event object
(
eventObject) to the listener object method. The event object has properties that contain
information about the event. You can use these properties to write code that handles the event.
Finally, you call the
addEventListener() method (see
EventDispatcher.addEventListener()) on the component instance that broadcasts the event
to register the listener with the instance. When the instance dispatches the event, the listener is
called.
For more information, see “EventDispatcher class” on page 415.
Example
This example, written on a frame of the Timeline, sends a message to the Output panel when a
button called
checkBoxInstance is clicked. The first line of code creates a listener object called
form. The second line defines a function for the click event on the listener object. Inside the
function is a
trace() statement that uses the event object that is automatically passed to the
function (in this example,
eventObj) to generate a message. The target property of an event
object is the component that generated the event (in this example,
checkBoxInstance). The
CheckBox.selected property is accessed from the event objects target property. The last line
calls
addEventListener() from checkBoxInstance and passes it the click event and the form
listener object as parameters.
form = new Object();
form.click = function(eventObj){
trace("The selected property has changed to " + eventObj.target.selected);
}
checkBoxInstance.addEventListener("click", form);
The following code also sends a message to the Output panel when checkBoxInstance is
clicked. The
on() handler must be attached directly to checkBoxInstance:
on(click){
trace("check box component was clicked");
}
See also
EventDispatcher.addEventListener()