ActionScript 3:如何使用匿名函数删除 EventListener
我写的代码如下。
问题是我无法删除 Event.COMPLETE
事件侦听器,并且当我调用 loadData
函数两次或更多次时,它会工作 2 次或更多次。抱歉我的英语不好,解释也更糟糕,但我今天需要修复它,但我不知道该怎么做。
我认为代码非常明显。请帮忙!
var ldr:URLLoader = new URLLoader();
function loadData(text_place, scrollbar, fileURL:String):void {
text_place.wordWrap = true;
var f:TextFormat = new TextFormat();
f.align = TextFormatAlign.RIGHT;
text_place.setTextFormat(f);
ldr.dataFormat = URLLoaderDataFormat.TEXT;
ldr.load(new URLRequest(fileURL));
ldr.addEventListener(Event.COMPLETE, function ldr_complete(evt:Event){
initText(text_place, ldr.data, scrollbar);
});
ldr.addEventListener(IOErrorEvent.IO_ERROR, loadError);
}
function initText(text_place:TLFTextField, fileContent, scrollbar):void {
ldr.removeEventListener(IOErrorEvent.IO_ERROR, loadError);
text_place.htmlText = "";
text_place.tlfMarkup = fileContent;
scrollbar.update();
trace("Data loaded");
}
function loadError(e:IOErrorEvent):void {
trace("Error loading an external file.");
}
I have written code as follows.
Problem is that I can't remove Event.COMPLETE
event listener and when I call the loadData
function twice or more, it works 2 times or more. Sorry for my bad english and worse explanation but I need to fix it today and I don't know what to do.
I think the code is pretty obvious. please help!
var ldr:URLLoader = new URLLoader();
function loadData(text_place, scrollbar, fileURL:String):void {
text_place.wordWrap = true;
var f:TextFormat = new TextFormat();
f.align = TextFormatAlign.RIGHT;
text_place.setTextFormat(f);
ldr.dataFormat = URLLoaderDataFormat.TEXT;
ldr.load(new URLRequest(fileURL));
ldr.addEventListener(Event.COMPLETE, function ldr_complete(evt:Event){
initText(text_place, ldr.data, scrollbar);
});
ldr.addEventListener(IOErrorEvent.IO_ERROR, loadError);
}
function initText(text_place:TLFTextField, fileContent, scrollbar):void {
ldr.removeEventListener(IOErrorEvent.IO_ERROR, loadError);
text_place.htmlText = "";
text_place.tlfMarkup = fileContent;
scrollbar.update();
trace("Data loaded");
}
function loadError(e:IOErrorEvent):void {
trace("Error loading an external file.");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需避免编写函数封装并扩展完整函数传递的参数的范围,以便它可以访问它们。
just avoid writing function enclosures and extend the scope of the complete function's passed arguments so it can access them.
如果您想在事件触发后停止侦听事件,则可以取消注册匿名侦听器本身:
但如果您还想在事件完成时停止侦听来自同一调度程序的其他事件,例如您的 IOErrorEvent.IO_ERROR 监听器,您仍然需要引用该监听器才能将其删除。
if you want to stop listening for an event after it triggered, you can unregister the anonymous listener in itself:
But if you also want to stop listening for other events from the same dispatcher when it completes, such as your
IOErrorEvent.IO_ERROR
listener, you'd still need a reference to that listener to remove it.有一个更简单的方法。不要删除事件侦听器,而是关闭加载程序。
根据文档:
There is a simpler way. Instead of removing event listeners, close the loader.
Per the documentation: