apscience
apscience

Reputation: 7273

Why doesn't removing event listeners work?

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?

Upvotes: 5

Views: 453

Answers (1)

laurent
laurent

Reputation: 90863

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.

Upvotes: 3

Related Questions