Weakly referenced listeners

I never paid a lot of attention to the 5th parameter of addListener, the useWeakReference parameter.

But the other day I decided to play a bit with it. As a reminder of its function I created a small test.

To create it yourself, perform the following steps:
1. Create new AS3 movieclip in Flash IDE
2. Set framerate to 1 fps
3. Copy following code in the first frame:

// create two event listener objects
var bot1: Object = {
  spam: function(anEvent: Event): void 
  {
    trace('bot1: spam');
  }
};
var bot2: Object = {
  spam: function(anEvent: Event): void 
  {
    trace('bot2: spam');
  }
};
// call spam every frame
this.addEventListener(
  Event.ENTER_FRAME, bot1.spam, false, 0, false
);
this.addEventListener(
  Event.ENTER_FRAME, bot2.spam, false, 0, true
);
// frame counter
var frame: int = 1;
// perform different action every frame
function demo(anEvent: Event): void
{
  switch(frame)
  {
    case 1:
    case 3:
      trace('Garbage collecting');
      System.gc();
      break;
    case 2:
      trace('Removing reference');
      bot1 = null;
      bot2 = null;
      break;
    case 4:
      trace('Removing demo');
      this.removeEventListener(Event.ENTER_FRAME, demo);
      break;
  }
  frame++;
}
// call demo every frame
trace('Adding demo');
this.addEventListener(Event.ENTER_FRAME, demo);

Even though the reference to bot1 is cleared, you will still see trace messages with “bot1: spam”; because there is still a reference to the spam listener method inside bot1. So bot1 does not get removed by the garbage collector.