User Guide
Event handler scope 175
When attached to a button object, the play() function applies to the Timeline that contains the
button—that is, the button’s parent Timeline. But when the
on(press) handler is attached to a
movie clip object, the
play() function call applies to the movie clip that bears the handler. If you
attach the following code to a movie clip, it plays the parent Timeline:
// Attached to movie clip
on(press) {
_parent.play(); // plays parent Timeline
}
Within an event handler or event listener definition, the same play() function would apply to
the Timeline that contains the function definition. For example, suppose you declare the
following
my_mc.onPress event handler method on the Timeline that contains the movie clip
instance
my_mc:
// Function defined on a Timeline:
my_mc.onPress = function() {
play(); //plays Timeline that it is defined on
};
If you want to play the movie clip that defines the onPress event handler, you have to refer
explicitly to that clip using the
this keyword, as follows:
// Function defined on root Timeline
my_mc.onPress = function () {
this.play(); // plays Timeline of my_mc clip
};
However, the same code placed on the root Timeline for a button instance would instead play the
root Timeline:
my_btn.onPress = function() {
this.play(); //plays root Timeline
};
For more information about the scope of the this keyword in event handlers, see “Scope of the
this keyword” on page 176.
ActionScript 2.0 example The following Loader class is used to load a text file and returns a
variable after it successfully loads the file.
class Loader {
var params_lv:LoadVars;
function Loader() {
params_lvL:LoadVars = new LoadVars();
params_lv.onLoad = onLoadVarsDone; // <-- this is a problem!
params_lv.load("foo.txt");
}
function onLoadVarsDone(success:Boolean):Void {
trace(params_lv.someVariable);
}
}