User Guide

168 Chapter 5: Handling Events
The following ActionScript classes define event handlers: “Button class”, “ContextMenu class”,
“ContextMenuItem class”, “Key class”, “LoadVars class”, “LocalConnection class”, “Mouse class”,
“MovieClip class”, “MovieClipLoader class”, “Selection class”, “SharedObject class”, “Sound
class”, “Stage class”, “TextField class”, “XML class”, and “XMLSocket class”. For more
information about the event handlers they provide, see each class entry in Flash ActionScript
Language Reference.
By default, event handler methods are undefined: when a particular event occurs, its
corresponding event handler is invoked, but your application doesnt respond further to the event.
To have your application respond to the event, you define a function with the function statement
and then assign that function to the appropriate event handler. The function you assign to the
event handler is then automatically invoked whenever the event occurs.
An event handler consists of three parts: the object to which the event applies, the name of the
object’s event handler method, and the function you assign to the event handler. The following
example shows the basic structure of an event handler:
object.eventMethod = function () {
// Your code here, responding to event
}
For example, suppose you have a button named next_btn on the Stage. The following code
assigns a function to the buttons
onPress event handler; this function advances the playhead to
the next frame in the Timeline:
next_btn.onPress = function () {
nextFrame();
}
Assigning a function reference
In the previous code, the nextFrame() function is assigned
directly to
onPress. You can also assign a function reference (name) to an event handler method
and later define the function, as shown in the following example:
// Assign a function reference to button’s onPress event handler method
next_btn.onPress = goNextFrame;
// Define goNextFrame() function
function goNextFrame() {
nextFrame();
}
Notice in the following example that you assign the function reference, not the functions return
value, to the
onPress event handler:
// Incorrect!
next_btn.onPress = goNextFrame();
// Correct.
next_btn.onPress = goNextFrame;
Receiving passed parameters
Some event handlers receive passed parameters that provide
information about the event that occurred. For example, the
TextField.onSetFocus event
handler is invoked when a text field instance gains keyboard focus. This event handler receives a
reference to the text field object that previously had keyboard focus.