title: How to make closure outer scope reference weak. Or any other workaround
body: <p><strong>Assumption 1.</strong> I have utility class called <code>Experiment</code>. It helps listening EnterFrame events on chosen sprites. The API looks following: <code>Experiment.listenEnterFrame(mySprite, onEnterFrameHandler);</code>.</p>
  
  <p><strong>Assumption 2.</strong> I want my <code>Experiment.listenEnterFrame</code> class to allow using anonymous handlers. I also want it to be memory-leak resistant (without any <code>cleanUp()</code> method), i.e. reference to mySprite should be weak.</p>
  
  <p>Here's the code:</p>
  
  <pre><code>package
  {
  import flash.display.Sprite;
  import flash.events.Event;
  import flash.system.System;
  import flash.utils.Dictionary;
  import flash.utils.setTimeout;
  
  public class Experiment extends Sprite
  {
      public function Experiment()
      {
          new MemoryLeakTest();
          new NoMemoryLeakTest();
          setTimeout(System.gc, 100);
      }
  
      private static var dict:Dictionary = new Dictionary(true);
  
      private static function listener(event:Event)
      {
          dict[event.currentTarget]();
      };
  
      public static function listenEnterFrame(dispatcher:Sprite, callback:Function):void
      {
          dict[dispatcher] = callback;
          dispatcher.addEventListener(Event.ENTER_FRAME, listener, false, 0, true);
      }
  }
  }
  
  import flash.display.Sprite;
  
  internal class MemoryLeakTest extends Sprite
  {
      function MemoryLeakTest():void
      {
          Experiment.listenEnterFrame(this, function () {
              trace("Memory leak");
          });
      }
  }
  
  internal class NoMemoryLeakTest
  {
      function NoMemoryLeakTest():void
      {
          Experiment.listenEnterFrame(new Sprite(), function () {
              trace("No Memory leak");
          });
      }
  }
  </code></pre>
  
  <p>In above example, the MemoryLeakTest instance is never removed - tracing "Memory leak" forever.</p>
  
  <p>My interpretation of that is that <code>callback</code> closure created in <code>MemoryLeakTest</code> keeps reference to outer scope, which is <code>MemoryLeakTest</code> instance itself. Because of this reference, <code>MemoryLeakTest</code> instance can't be garbage collected.</p>
  
  <p>Do you know any workaround, so I can use anonymous callbacks in my utility method without having to worry about memory freeing?</p>