R – Actionscript 3: Do you need to remove EventListeners

actionscript-3

In actionscript 3, I dynamically create objects to which I add EventListeners. These objects are added to arrays and might be removed again later. And others might be added later again. Each time I create an object, I add these EventListeners to them. However, is it necessary to remove these event listeners too, when deleting these objects? What happens when I lose all references to an object but don't delete these EventListeners? Do they stay somewhere in the memory, unreachable and unusuable, or does the GC clean them up?

Best Answer

Yes, you have to remove event listeners if you are not using weak references. GC won't clean up an object if there is a reference to it, and registering event listeners do create a reference to the object unless you set the useWeakReference parameter (the 5th parameter to the addEventListener method) to true while registering the event listener. Weak references won't be counted by the garbage collector.

//Using strong reference: needs to be removed by calling removeEventListener
sprite.addEventListener(Event.TYPE, listenerFunction, useCaptureBool, 0, false);

//Using a weak reference: no need to call removeEventListener
sprite.addEventListener(Event.TYPE, listenerFunction, useCaptureBool, 0, true);
Related Topic