views:

1138

answers:

4

Is there a way to determine which event listeners are registered with a display object? I want to remove all event listeners from a display object so that I can assign new ones based on context changes in the application.

+3  A: 

Glenn is right, there is no such thing as a removeAllListener or listAllListener method. Nevertheless, you could make your custum diplayObject implement the IEventDispatcher interface and keep track of all the listeners added or removed from your object.

jdecuyper
+4  A: 

jeceuyper is right ...

a side not though: DisplayObject extends EventDispatcher, which already does implement IEventDispatcher ... so to be more precise: you need to override addEventListener and removeEventListener to keep track of the listeners ...

a few technical details: i suggest you use Dictionary to store the handler functions ... a bit slower for insertion, but much faster for removal ... also, Dictionary supports weak references, which is quite important in the case of event handling ... also keep in mind, that useCapture allows to add the same handler twice ...

good luck then ... ;)

back2dos
Thanks for pointing that out back2dos!
jdecuyper
+1  A: 

back2dos has mentioned the approach you should use, what i did was extend the movieclip class and implemented all kinds of functions that i use on daily basis but are not part of the movieclip class. including the override for the addEventListener class

protected var listeners : Dictionary    = new Dictionary();
override public function addEventListener( type : String, listener : Function, useCapture : Boolean = false, priority : int = 0, useWeakReference : Boolean = true) : void
{
  var key : Object = {type:type,useCapture:useCapture};
    if( listeners[ key ] ) {
             removeEventListener( type, listeners[ key ], useCapture );
             listeners[ key ] = null;
    }
    listeners[ key ] = listener;

    super.addEventListener( type, listener, useCapture, priority, useWeakReference );
}
protected function removeListeners () : void
{
  try
  {
   for (var key:Object in listeners) {
           removeEventListener( key.type, listeners[ key ], key.useCapture );
               listeners[ key ] = null;
      }
  }catch(e:Error){}
}
Andy Jacobs
+1  A: 

This is sort of a hack, but in some (perhaps most cases), you can easily set the display object to null and re-initialize it and then re-configure it with zero visual disruption.

This has the added bonus of removing all event listeners.

Unless you are doing this in an app that already has hundreds of listeners and objects then it should work perfectly fine so long as you can tolerate reconfiguring your display object.

Obviously, you shouldn't do this on anything that is doing something crazy in the constructor like loading data.

Jasconius