User Guide
174 Chapter 5: Handling Events
Event handler scope
The scope, or context, of variables and commands that you declare and execute within an event
handler depends on the type of event handler you use: event handlers or event listeners, or
on()
and
onClipEvent() handlers. If you’re defining an event handler in a new ActionScript 2.0 class,
the scope also depends on how you define the event handler. This section contains both
ActionScript 1 and ActionScript 2.0 examples.
ActionScript 1 examples Functions assigned to event handler methods and event listeners (as
with all ActionScript functions that you write) define a local variable scope, but
on() and
onClipEvent() handlers do not.
For example, consider the following two event handlers. The first is an
onPress event handler
associated with a movie clip named
clip_mc. The second is an on() handler attached to the same
movie clip instance.
// Attached to clip_mc’s parent clip Timeline:
clip_mc.onPress = function () {
var color; // local function variable
color = "blue";
}
// on() handler attached to clip_mc:
on(press) {
var color; // no local variable scope
color = "blue";
}
Although both event handlers contain the same code, they have different results. In the first case,
the
color variable is local to the function defined for onPress. In the second case, because the
on() handler doesn’t define a local variable scope, the variable is defined in the scope of the
Timeline of the movie clip
clip_mc.
For
on() event handlers attached to buttons, rather than to movie clips, variables (as well as
function and method calls) are invoked in the scope of the Timeline that contains the button
instance.
For instance, the following
on() event handler produces different results that depend on whether
it’s attached to a movie clip or button object. In the first case, the
play() function call starts the
playhead of the Timeline that contains the button; in the second case, the
play() function call
starts the Timeline of the movie clip to which the handler is attached.
// Attached to button
on(press) {
play(); // plays parent Timeline
}
// Attached to movie clip
on(press) {
play(); // plays movie clip’s Timeline
}