View Single Post
Nutrox's Avatar Nutrox Nutrox is offline Super Moderator 17 Creative Assets 2006-11-15 #31 Old  
028 - Delegate Alternative
Last edited by Nutrox : 2006-11-22 at 04:23.
 
Following on from Codemonkey's look at the Delegate class, I actually use my own delegate-like class for fixing scope. This version allows you to pass custom arguments to the target method without overwriting any arguments that Flash might spit out, the standard Delegate class will overwrite those arguments.

Here is the AS2 class:

ActionScript Code:
  1. class cs.utils.Scope
  2. {
  3.     public static function rewire(scope:Object, func:Function):Function
  4.     {
  5.         var args:Array = [];
  6.  
  7.         if (arguments.length > 2)
  8.         {
  9.             args = arguments.splice(2, arguments.length - 2);
  10.         }
  11.         return function()
  12.         {
  13.             return func.apply(scope, args.concat(arguments));
  14.         }
  15.     }
  16. }
A good example of how to use the class would be with the XML.onLoad event:

ActionScript Code:
  1. import cs.utils.Scope;
  2.  
  3. var xml:XML = new XML();
  4. xml.ignoreWhite = true;
  5. xml.onLoad = Scope.rewire(this, xmlLoadHandler, "Hello!", xml);
  6.  
  7. xml.load("file.xml");
  8.  
  9. function xmlLoadHandler(word:String, xmlFile:XML, success:Boolean):Void
  10. {
  11.     if (!success)
  12.     {
  13.         // D'oh!
  14.     }
  15.     else
  16.     {
  17.         trace(this);           // _level0
  18.         trace(word);           // output: Hello!
  19.         trace(xmlFile == xml); // output: true
  20.         trace(this == xml);    // output: false
  21.     }
  22. }
As you can see the scope of the xmlLoadHandler will be _level0 instead of the XML object. Your custom arguments will be passed to method before any of the default ones that Flash might send (i.e. success).