Losing scope within a class

Maintaining scope while writing object orientated code in Flash isn't always easy. Let's say you are loading some XML within a method in a class as in the following example:
class ExampleClass {
  var xml:XML;

  public function ExampleClass() {
    xml = new XML();
    xml.load(data.xml);
  }
}
When the XML is done loading it is handled by a method on the XML class that the developer is meant to define such as:
xml.onLoad = function { // do something with the XML. }
Well, what if you want to do something within the context of the compositing class (ExampleClass) at this point. Any code that you put within the onLoad function definition will execute within the scope of the XML object and not your class. The XML object also has no reference to the parent class like a MovieClip does and you can not dynamically add properties to the XML object like a MovieClip either which would allow you to make an internal reference to the compositing class.

Fortunately Flash provides a really cool component for maintaining scope. Most developers don't even know this exists because it is a component and not listed with the main ActionScript Classes. The mx.utils.Delegate class will allow you to define the onLoad function, but within the scope of whatever object you specify. Let's see an example:
import mx.utils.Delegate;
class ExampleClass {
  var xml:XML;

  public function ExampleClass() {
    xml = new XML();
    xml.onLoad = Delegate.create(this,onXMLLoad);
    xml.load(data.xml);
  }

  private function onXMLLoad(success:Boolean):void {
    // this code will now execute within the scope
    // of the ExampleClass class.
  }
}
This works great in a variety of situations such as:
- adding event listeners
- defining event handlers like onRelease on child MovieClips of a class
- LoadVars
- NetStream

This is no longer a problem in AS3 because scope is automatically remembered which makes life a lot easier. Once you start using the Delegate class, you'll never know how you got along with out it.

Comments are closed.