EasyManua.ls Logo

MACROMEDIA FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH - Page 346

MACROMEDIA FLASH 8-LEARNING ACTIONSCRIPT 2.0 IN FLASH
830 pages
Print Icon
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
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,...
}
}

Table of Contents

Related product manuals