View Single Post
Codemonkey's Avatar Codemonkey Codemonkey is offline Super Moderator 2006-11-15 #30 Old  
027 - Fixing scope with Delegates (as2)
Last edited by Codemonkey : 2006-11-28 at 01:11.
 
If for some reason you think "Why is this or that tracing undefined??" or "Why isn't my function executing omg!". Then for the love of God, think of Delegates!! Search Ultrashock on the word "scope" and "Delegate" and don't ask us again please

Classic example:

ActionScript Code:
  1. class MyXMLParser {
  2.     var books:Array = new Array();
  3.  
  4.     function doIt() {
  5.         var xml:XML = new XML();
  6.         xml.onLoad = parseXML;
  7.         xml.load("books.xml");
  8.     }
  9.  
  10.     function parseXML(success:Boolean) {
  11.         // parse xml stuff
  12.         books.push(book_from_xml); // BUZZ, can't find books!
  13.     }
  14. }
Books couldn't be found, because when the xml object calls parseXML, the scope is in the xml object, not MyXMLParser. And so you can't access books because it isn't in the xml object.

Fix this with a Delegate:

ActionScript Code:
  1. import mx.utils.Delegate;
  2.  
  3. class MyXMLParser {
  4.     var books:Array = new Array();
  5.  
  6.     function doIt() {
  7.         var xml:XML = new XML();
  8.         xml.onLoad = Delegate.create(this, parseXML);
  9.         xml.load("books.xml");
  10.     }
  11.  
  12.     function parseXML(success:Boolean) {
  13.         // parse xml stuff
  14.         books.push(book_from_xml); // DING, can find books!
  15.     }
  16. }