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.
This looks very nice but i dont like a class property, when there is no need to e.g. when you read your xml once to set up a configuration.
But this bring me to the idea that the local scope of x can be used in the delegated onLoad-handler like:
import mx.utils.Delegate;
class Test {
private var member:String = “I am a member of Test”;
public function Test(){
init();
}
private function init(){
var x = new XML();
x.ignoreWhite = true;
x.onLoad = Delegate.create(this, function(success){
trace(“success: ” + success);
trace(“xml: ” + x.firstChild);
trace(“Test member: ” + member);
});
x.load(“test.xml”);
}
}
yes, but then we’re back into nested functions, which is what I was trying to avoid in the first place.
Plus, you can always delete your xml object once you are done with it.
mmmmm non-nested!
When I read about Delegate in LiveDocs and then tried to apply this class to my projects, I have found Delegate class works with Everything I Need!
Great minds think alike 😉
Having recently finished a blog article with this same solution I ventured over here as this is where I found my the old solution I was using. And you beat me to the punch by 4 days. Keep up the good work!