BIT-101 [2003-2017]

Scope in AS2, beaten like a dead horse!


OK, this is probably my fourth or fifth post on this, each with a different recommendation for handling! I just read this post by Sam at rewindlife, showing how you could use the Delegate class (of which I am already a convert) to handle the callbacks of plain Flash buttons. I thought, hmm….if it can handle button callbacks, why not xml callbacks? Did a quick test:

import mx.utils.Delegate;

class Test {
	private var member:String = "I am a member of Test";
	private var x:XML;

	public function Test(){
		init();
	}
	private function init(){
		x = new XML();
		x.ignoreWhite = true;
		x.onLoad = Delegate.create(this, parse);
		x.load("test.xml");
	}
	private function parse(success){
		trace("success: " + success);
		if(success){
			trace("xml: " + x.firstChild);
			trace("Test member: " + member);
		}
	}
}

So what’s going on here? We create a new Delegate and assign it as the onLoad handler of the xml object. You’ll see in the function, parse, which we passed to the delegate, it receives the success parameter, which is what onLoad receives. But you also can see the scope of the function remains the class, not the xml object.

The only thing is that you’ve lost your reference to the xml object itself, which now contains your loaded xml document. You have to make the xml object a member of the class, and access it that way. If you created it as a local variable, it may be gone.

Actually, I’m sure that the delegate would hold a reference to a local var xml object somewhere, as it has to exist long enough to fire the onLoad event. I’m not sure if it releases it when it’s done, allowing it to be garbage collected or not. If so, there might be some way to hack around and find the reference some way. This is purely curious conjecture. I’d recommend doing it the way it is coded above.

« Previous Post
Next Post »