Weak Listeners

Garbage collection can be a big deal when writing complex programs in Actionscript. Not removing EventListeners is probably one of the biggest sources of AS holding onto memory it doesn’t need.

There is a very easy way to allow GC to handle your event listener clean-up for you when creating a new event listener – the useWeakReference argument.

Here is some standard code we’ve all done million times when creating a button:

The two arguments are pretty straight forward the first is the event we’re listing for and the second is the function that is called once the event is fired, but there are actually 5 arguments that can be passed to addEventListener() here is the method definition:

the 5th argument (useWeakReference) is false by default but by setting to true, this eventListener will be automatically removed and freed for Garbage Collection when required.

Here is the new eventListener code updated to make use of useWeakReference.

Leave a Reply

Your email address will not be published. Required fields are marked *