Actionscript 3: Force program to wait until event handler is called
I have an AS 3.0 class that loads a JSON file in using a URLRequest.
package {
import flash.display.MovieClip;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.Event;
public class Tiles extends MovieClip {
private var mapWidth:int,mapHeight:int;
private var mapFile:String;
private var mapLoaded:Boolean=false;
public function Tiles(m:String) {
init(m);
}
private function init(m:String):void {
// Initiates the map arrays for later use.
mapFile=m;
// Load the map file in.
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, mapHandler);
loader.load(new URLRequest("maps/" + mapFile));
}
private function mapHandler(e:Event):void {
mapLoaded=true;
mapWidth=3000;
}
public function getMapWidth():int {
if (mapLoaded) {
return (mapWidth);
} else {
return(-1);
}
}
}
}
When the file is finished loading, the mapHandler event makes changes to the class properties, which i开发者_运维问答n turn are accessed using the getMapWidth function. However, if the getMapwidth function gets called before it finishes loading, the program will fail.
How can I make the class wait to accept function calls until after the file is loaded?
private function mapHandler(e:Event):void {
if (mapLoaded) {
mapLoaded=true;
mapWidth=3000;
return (mapWidth);
} else {
getMapWidth()
}
}
public function getMapWidth():int
return(-1);
}
This might solve your problem, why are checking it in getMapWidth when there is no need of it.
Okay, so I figured out what I needed to do. The problem was with the code on my main timeline:
trace(bg.getMapWidth())
;
I forgot that the code only executed once without an event listener on the main timeline, like this
stage.addEventListener(Event.ENTER_FRAME, n);
function n(e:Event):void
{
trace(bg.getMapWidth());
}
Now the width is returned once per frame, and everything works properly. Thanks for your help ;)
精彩评论