Weakly referenced listeners

Briefly, in ActionScript 3.0, memory management that you do not explicitly control is handled behind the scenes by the garbage collector. When you are no longer referencing an object in your application, it is marked for cleanup, and the garbage collector periodically sweeps through your application discarding unneeded items, freeing up memory along the way. However, if a reference to an object remains, the garbage collector can’t know that the object should be purged from memory.

Try as we might to be good, it’s not uncommon for developers to forget to remove event listeners in their code (see the section “Removing Event Listeners”). However, a distant next-best thing is a weakly referenced listener.

Simply put, weakly referenced listeners aren’t supervised by the garbage collector and, therefore, don’t have to be manually marked for removal. If only weak references to an object remain after youhave finished using it, then the object is eligible for collection.

Using this option is very simple. All you need to do is change the weakReference setting of the addEventListener() method from its default value of false, to true. Because it’s the third optional parameter, values for the first and second parameters must be included so Flash knows which parameter you are trying to set. You will rarely need to change those values, so you can use their aforementioned defaults (false for useCapture and 0 for priority).

So, our preference is to use the addEventListener() method with this syntax:

eventTarget.addEventListener(EventType.EVENT_NAME, eventResponse, false, 0, true);

If you get in the habit of using this syntax, you will be far less likely to run into memory management problems due to lax code maintenance. Remember, this is not a substitute for removing your unneeded listeners explicitly. However, it’s a backup plan, and a best practice that is easy to adopt.

Post A Comment

Anti-Spam Quiz: