Simplifying Garbage Collection with CASA Lib

Written by Mike Creighton on December 21st, 2008

One of the most important things in ActionScript 3 is adhering to good garbage collection practices. With the release of CASA Lib for AS3, we’ve done our best to make that chore as easy as possible—extending the benefits to your own classes and work flow.

Every class that can be instantiated in CASA Lib for AS3 implements the IDetroyable interface. This means when it’s time to offer a given instance up for garbage collection, you only need to type this:

myCasaClass.destroy();
myCasaClass = null;

But we’ve gone an extra step to make garbage collection easier. With ActionScript 3 came a robust and reliable event model that simply wasn’t present in ActionScript 2. However, one of the chores that came along with this was having to “manually” remove all your event listeners when it was time to get rid of a class instance.

Every class in CASA Lib that’s capable of dispatching events either extends the RemoveableEventDispatcher class or implements the IRemovableEventDipatcher interface. When you call the destroy() method for these classes, all your event listeners are automatically removed. In addition to this, you’ve got access to a few very useful methods:

  • removeEventListeners - Removes all event listeners
  • removeEventsForListener - Removes all events associated with a specified listener
  • removeEventsForType - Removes all event listeners that were listening for a specific event type

All the display object classes in the org.casalib.display package not only implement the IRemovableEventDispatcher interface, but they also automatically remove themselves from their parent (if they’ve got one) when you call destroy().

To make the most of CASA Lib for AS3, when you would normally extend the core AS3 classes like EventDispatcher, MovieClip, Sprite, Bitmap, or TextField, you should start extending these CASA Lib classes:

Then, just override the destroy() method, adding the extra garbage cleanup that you need in your own classes. Finally, call super.destroy() in the last line of the overridden function.

Leave a Reply

Leave a Comment