88 Chapter 4: Handling Events
Creating movie clips with button states
When you attach an on() handler to a movie clip, or assign a function to one of the MovieClip
mouse event handlers for a movie clip instance, the movie clip responds to mouse events in the
same way as a button does. You can also create automatic button states (Up, Over, and Down) in
a movie clip by adding the frame labels
_up, _over, and _down to the movie clip’s Timeline.
When the user moves the mouse over the movie clip or clicks it, the playhead is sent to the frame
with the appropriate frame label. To designate the hit area used by a movie clip, you use the
hitArea property of the MovieClip class.
To create button states in a movie clip:
1 Select a frame in a movie clip’s Timeline to use as a button state (Up, Over, or Down).
2 Enter a frame label in the Property inspector (_up, _over, or _down).
3 To add additional button states, repeat steps 1–2.
4 To make the movie clip respond to mouse events, do one of the following:
■ Attach an on() event handler to the movie clip instance, as discussed in “Using button and
movie clip event handlers” on page 87.
■ Assign a function to one of the movie clip object’s mouse event handlers (onPress,
onRelease, and so forth), as discussed in “Using event handler methods” on page 83.
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’re using: event handlers or event listeners, or
on() and onClipEvent() handlers.
Functions assigned to event handler methods and event listeners (like 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 scopes to 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 scoped to the Timeline that contains the button instance.