为什么删除事件侦听器不起作用? [英] Why doesn't removing event listeners work?
问题描述
我的构造函数中有这个:
I have this in my constructor:
addEventListener(Event.REMOVED_FROM_STAGE, actualDestroy);
这在实际销毁中:
public function actualDestroy(e:* = null){
removeEventListener(Event.REMOVED_FROM_STAGE,actualDestroy);
if(this.parent){
this.parent.removeChild(this);
}
}
问题是我收到错误:错误 #2094:事件调度递归溢出.如果 this.parent 不存在,为什么 removechild 不断被调用?为什么删除事件侦听器不起作用?
The problem is I get Error: Error #2094: Event dispatch recursion overflow. Why does removechild keep getting called if this.parent does not exist? Why doesn't removing event listeners work?
推荐答案
事件名称具有误导性.removedFromStage
,根据文档,在显示对象即将从显示列表中删除时分派".换句话说,这就是您的代码中发生的事情:
The name of the event is misleading. removedFromStage
, according to the docs, is "dispatched when a display object is about to be removed from the display list". In other words, this is what's happening in your code:
- 在代码中的某处调用
parent.removeChild(this)
actualDestroy
立即被调用.此时对象还在显示列表中,所以this.parent != null
- 在
actualDestroy
中,您再次调用parent.removeChild(this)
. - 转到第 2 步
- Somewhere in your code, you call
parent.removeChild(this)
actualDestroy
is immediately called. At this point, the object is still in the display list, sothis.parent != null
- In
actualDestroy
, you callparent.removeChild(this)
again. - Go to step 2
所以为了解决这个问题,你可能想要重构你的代码(一个对象从显示列表中删除自己从来都不是一个好主意),或者使用一些像 beingRemoved
这样的布尔值来检查是否该对象已从列表中删除.在这种情况下,不要在 actualDestroy
中调用 parent.removeChild(this)
.
So to fix the issue, you might want to refactor your code (an object removing itself from the display list is never a good idea anyway), or perhaps use some boolean like beingRemoved
to check whether the object is being removed from the list already. In which case, don't call parent.removeChild(this)
in actualDestroy
.
这篇关于为什么删除事件侦听器不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!