346
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 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
this.onLoad
event handler
when the text file is successfully loaded, and the
onLoadVarsDone()
function is invoked with
this
set to LoadVars, not TextLoader. 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, the
onLoadVarsDone()
function is expecting a
params_lv.params_lv
instance that does not exist.
To correctly invoke the
onLoadVarsDone()
method in the scope of the TextLoader 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 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,...
}
}
Summary of Contents for FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH
Page 1: ...Learning ActionScript 2 0 in Flash...
Page 8: ...8 Contents...
Page 18: ...18 Introduction...
Page 30: ...30 What s New in Flash 8 ActionScript...
Page 66: ...66 Writing and Editing ActionScript 2 0...
Page 328: ...328 Interfaces...
Page 350: ...350 Handling Events...
Page 590: ...590 Creating Interaction with ActionScript...
Page 710: ...710 Understanding Security...
Page 730: ...730 Debugging Applications...
Page 780: ...780 Deprecated Flash 4 operators...
Page 830: ...830 Index...