Actionscript 3:强制程序等待,直到调用事件处理程序
我有一个 AS 3.0 类,它使用 URLRequest 加载 JSON 文件。
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);
}
}
}
}
文件加载完成后,mapHandler 事件会对类属性进行更改,然后使用 getMapWidth 函数来访问这些属性。但是,如果 getMapwidth 函数在加载完成之前被调用,则程序将失败。
如何让类等到文件加载后才接受函数调用?
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 in 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能会解决您的问题,为什么在不需要时在 getMapWidth 中检查它。
This might solve your problem, why are checking it in getMapWidth when there is no need of it.
好吧,所以我想出了我需要做什么。问题出在我的主时间线上的代码:
trace(bg.getMapWidth())
;我忘记了代码只在主时间轴上没有事件监听器的情况下执行一次,就像这样
现在每帧返回一次宽度,并且一切正常。感谢您的帮助 ;)
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
Now the width is returned once per frame, and everything works properly. Thanks for your help ;)