User Guide

176 Chapter 5: Handling Events
This code cannot work correctly because there is a problem involving scope with the event
handlers, and what
this refers to is confused between the onLoad event handler and the class.
The behavior that you might expect in this example is that the
onLoadVarsDone() method will
be invoked in the scope of the Loader object; but it is invoked in the scope of the LoadVars object
because the method has been extracted from the Loader object and grafted onto the LoadVars
object. The LoadVars object then invokes the
this.onLoad event handler when the text file has
successfully loaded, and the
onLoadVarsDone() function is invoked with this set to LoadVars,
not Loader. The
params_lv object resides in the this scope when it is invoked, even though the
onLoadVarsDone() function relies on the params_lv object by reference. Therefore, it is
expecting a
params_lv.params_lv instance that does not exist.
To correctly invoke the
onLoadVarsDone() method in the scope of the Loader object, you can
use the following strategy: Use a function literal to create an anonymous function that calls the
desired function. The
owner object is still visible in the scope of the anonymous function, so it
can be used to find the calling Loader object.
class Loader {
var params_lv:LoadVars;
function Loader() {
params_lv:LoadVars = new LoadVars();
var owner:Loader = this;
params_lv.onLoad = function (success:Boolean) {
owner.onLoadVarsDone(success); }
params_lv.load("foo.txt");
}
function onLoadVarsDone(success:Boolean):Void {
trace(params_lv.someVariable);
}
}
Scope of the this keyword
The this keyword refers to the object in the currently executing scope. Depending on what type
of event handler technique you use,
this can refer to different objects.
Within an event handler or event listener function, this refers to the object that defines the
event handler or event listener method. For example, in the following code,
this refers to my_mc:
// onPress() event handler attached to _level0.my_mc:
my_mc.onPress = function () {
trace(this); // displays '_level0.my_mc'
}
Within an on() handler attached to a movie clip
, this refers to the movie clip to which the
on() handler is attached, as shown in the following code:
// Attached to movie clip named my_mc
on(press) {
trace(this); displays '_level0.my_mc'
}