// you’re reading...

ActionScript 3.0

EventDispatcher - removeEventListener and the Delegate.

This hurdle took about forty-five minutes out of my life today so I thought that it would be nice to go ahead and put it out in the atmosphere one more time.

When you add an eventListener to something and later want to remove it so as to not have your code exsanguinate- (I guess you wouldn't call it that with a memory leak-but you get my meaning) you would do well to call removeEventlistener when you no longer need to be listening for that event.

The problem is that the following will fail silently and oh so miserably:

Actionscript:
  1. function addEventListeners(){
  2.  
  3. guy.addEventListener("scream",Delegate.create( this, coverEars))
  4.  
  5. }
  6.  
  7. function coverEars(ev:Object):Void{
  8.  
  9. guy.removeEventListener("scream", coverEars);
  10. //do whatever you're supposed to do to respond
  11. }

You actually have to go through the extra steps of:

Actionscript:
  1. function addEventListeners(){
  2.  
  3. earDelegate:Function=Delegate.create(this,coverEars);
  4.  
  5. guy.addEventListener("scream",earDelegate)
  6.  
  7. }
  8.  
  9. function coverEars(ev:Object):Void{
  10.  
  11. guy.removeEventListener("scream", earDelegate);
  12. //do whatever you're supposed to do to respond
  13. }

I had actually found some links that demonstrate this even better but they are on my office computer so I'll have to add them on here later.

Discussion

4 comments for “EventDispatcher - removeEventListener and the Delegate.”

  1. If you use the alternative Delegate class by dynamicflash.com, it passes a reference to the Delegate to the Delegates target, in addition to the event object. You can then use this to remove the event listener.

    http://dynamicflash.com/2005/05/delegate-version-101/

    Also, if you use grant skinners GDispatcher class instead, it comes with methods to remove all listeners etc.

    http://www.gskinner.com/blog/archives/000027.html

    Posted by Phil Douglas | April 29, 2006, 2:47 am
  2. guy.addEventListener(”scream”,Delegate.create( this, coverEars))
    in this case Delegate.create always will ber return a _new_ function, not coverEars
    thats because you can’t remove listener, added by this method.

    Posted by begemoth | April 29, 2006, 7:46 am
  3. Do you mean in the first example?

    Posted by diamondtearz | April 29, 2006, 8:03 am
  4. First a disclaimer - it’s Saturday a.m. so I’m slightly hungover… ;-)
    If you only need to remove it in your handler function I believe arguments.caller will give you a reference to your listener. Handy but not as versatile as holding a reference.

    A.

    Posted by andrew | April 29, 2006, 8:24 am

Post a comment