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.
To remove all event listeners from an element: Use the cloneNode() method to clone the element. Replace the original element with the clone. The cloneNode() method copies the node's attributes and their values, but doesn't copy the event listeners.
You can remove all event listeners from a DOM element in Javascript by replacing the element with a deep clone of itself. elem. cloneNode(...) will not clone the event listeners of the source element.
Add the event listener in the useEffect hook. Return a function from the useEffect hook. Use the removeEventListener method to remove the event listener when the component unmounts.
The event listeners need to be removed due to following reason. Avoid memory leaks, if the browser is not handled it properly. Modern browsers will garbage collect event handlers of removed DOM elements but it is not true in cases of legacy browses like IE which will create memory leaks.
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){}
}
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 ... ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With