Why doesn't removing event listeners work?

巧了我就是萌 提交于 2019-12-23 09:57:58

问题


I have this in my constructor:

addEventListener(Event.REMOVED_FROM_STAGE, actualDestroy);

And this in actualDestroy:

    public function actualDestroy(e:* = null){
        removeEventListener(Event.REMOVED_FROM_STAGE,actualDestroy);
        if(this.parent){
            this.parent.removeChild(this);
        }
    }

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?


回答1:


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:

  1. Somewhere in your code, you call parent.removeChild(this)
  2. actualDestroy is immediately called. At this point, the object is still in the display list, so this.parent != null
  3. In actualDestroy, you call parent.removeChild(this) again.
  4. Go to step 2

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.



来源:https://stackoverflow.com/questions/8252211/why-doesnt-removing-event-listeners-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!