This code cannot work correctly because there is a problem involving scope with the event
handlers, and what
this
The behavior that you might expect in this example is that the
will be invoked in the scope of the TextLoader object; but it is invoked in the scope of the
LoadVars object because the method was extracted from the TextLoader object and grafted
onto the LoadVars object. The LoadVars object then invokes the
when the text file is successfully loaded, and the
set to LoadVars, not TextLoader. The
this
it is invoked, even though the
reference. Therefore, the
instance that does not exist.
To correctly invoke the
you can use the following strategy: use a function literal to create an anonymous function that
calls the desired function. The
function, so it can be used to find the calling TextLoader object.
// TextLoader.as
class TextLoader {
private var params_lv:LoadVars;
public function TextLoader() {
params_lv = new LoadVars();
var owner:TextLoader = this;
params_lv.onLoad = function (success:Boolean):Void {
owner.onLoadVarsDone(success);
}
params_lv.load("http://www.helpexamples.com/flash/params.txt");
}
private function onLoadVarsDone(success:Boolean):Void {
_level0.createTextField("my_txt", 999, 0, 0, 100, 20);
_level0.my_txt.autoSize = "left";
_level0.my_txt.text = params_lv.monthNames; //
January,February,March,...
}
}
346
Handling Events
refers to is confused between the
params_lv
onLoadVarsDone()
onLoadVarsDone()
onLoadVarsDone()
object is still visible in the scope of the anonymous
owner
onLoad
onLoadVarsDone()
this.onLoad
onLoadVarsDone()
object resides in the
function relies on the
function is expecting a
method in the scope of the TextLoader object,
event handler and the class.
method
event handler
function is invoked with
scope when
this
object by
params_lv
params_lv.params_lv
Need help?
Do you have a question about the FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH and is the answer not in the manual?