title: Implementing callbacks in AS3
body: <p>I am working on a set of "generic" classes I use frequently in different AS3 projects. One of these classes is the Image class (extends MovieClip) which simply takes an URL, generates a loader than loads it and adds it as a child. In the aim of making it more generic, I thought of adding a callback as a parameter that could contain certain messages related to resizing the image and such (I can't resize any Image before the loader inside it is loaded since it's width and height will be 0 until then so it's necessary to wait for loading and handling such operations using event listeners in parent MovieClips is not convenient if there's a huge amount of images being loaded).</p> 
  
  <p>Here is my current implementation:</p>
  
  <pre><code>public class Image extends MovieClip {
  
      public var self:MovieClip; //fixes scope issues when nesting functions
      private var url:String;
      private var callback:Function;
  
      public function Image(url:String, callback:Function) {
          this.self = this; //fixes scope issues when nesting functions
          this.url = url;
          this.callback = callback;
          this.loadAndDraw();
      }
  
      public function loadAndDraw():void {
          var l:Loader = new Loader();
          l.contentLoaderInfo.addEventListener(Event.COMPLETE, function doneLoading(evt:Event) {
              self.addChild(evt.currentTarget.loader); 
              callback();
          });
          l.load(new URLRequest(this.url));
      }
  
  }
  </code></pre>
  
  <p>Now, the problem with this is I'm having trouble writing the callback functions. I'm uncertain about how am I meant to refer to the 'caller', which makes me think there's a better way of doing this. What do you suggest?</p>