Version 6, last updated by Kirill Mourzenko at September 30, 2008 14:19 UTC

The Dictionary class in AS3 provides a very useful weak reference functionality. In Handy Toolset the com.kirillam.handy.datastructures.WeakReference class offers this functionality as well for AS2. It is a much more basic datastructure than a Dictionary. It stores a single object in a weak manner. The way you use this is simple.

  com.kirillam.handy.datastructures.WeakReference;

  ...

  var r : WeakReference = new WeakReference( new Object() );
  traceI( r.object);

Unless this object is also referenced by some other variable or datastructure it will eventually be garbage collected. For efficiency reasons not all objects that are viable for garbage collection get collected at once, but they do eventually get their turn. Once the object is garbage collected the r.object property returns null. The weakReference object also sends a HATEvent.REMOVED event after the object is garbage collected. It's not sent at the same time as it happens but it is sent on the same frame.

There is a more complex datastructore implemented by com.kirillam.handy.datastructures.Set that allows storage of multiple objects. When adding objects into a set you are allowed to specify which way it should be stored.

  com.kirillam.handy.datastructures.Set;

  ...

  var r : Set = new Set();
  r.add( new Object() );
  r.add( new Object(), true );

The 2nd object added will be garbage collected unless pointed to by something else as well.

The Set datastructure is very useful for storing collections of objects. Here's the full API to it:

  // Adds an object to the set if it's not already in it.
  // Also allows you to store it in a weak manner allowing it to be garbage collected.
  public function add( o : Object, useWeakReference : Boolean )

  // Removes an object from the set.
  public function remove( o : Object )

  // Empties the set.
  public function removeAll()

  // Removes and returns some object from the set.
  public function takeOut() : Object

  // Returns true if the object is in the set, false if not.
  public function isIn( o : Object ) : Boolean

  // Returns the object if it's in the set, given its hatId.
  public function getMemberById( id : String ) : Object

  // Allows the same functionality as a for-in loop.
  // For each member of the set it executes the method of the object passing the member as an argument.
  public function forEach( target : Object, method : Function )

When adding an event handler to a HATObject by default it will be stored using a WeakReference unless you specify that you want to use a strong reference as a the fourth argument to the handle method.