yerekla
yerekla

Reputation: 111

Actionscript 3: Do you need to remove EventListeners?

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?

Upvotes: 3

Views: 872

Answers (2)

grapefrukt
grapefrukt

Reputation: 27045

When you have event listeners on an object you won't ever loose all references to it, so it'll stay in memory indefinitely. You need to make sure you always remove any listeners you set. You can set them using weak references, but that's not really a solution, it's better to remove them explicitly.

Upvotes: 0

Amarghosh
Amarghosh

Reputation: 59461

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);

Upvotes: 4

Related Questions