Xml, Scope and the Delegate
One of the problems/complaints I often here about loading XML data into Flash is how to keep the scope straight without having to use a hack. Thankfully Macromedia has provided a solution, the 'mx.utils.Delegate' class.
The Delegate gets mentioned alot when using controls and event listeners, and rightly so, but it also provides a very nice solution to xml scope problem. The great thing about the Delegate is that you can easily control the scope within the called function, which is exactly what you want once the xml has loaded and you begin trying to use the data.
Without the Delegate you can either rely on scope chain the find what you are after (in the example below the 'myText_txt' text field) or you have to hack something in (a property to use for scope, in the example I used '_parent').
Rely on scope chain
function xmlLoaded(success){
if (success){
myText_txt.text += myXml.toString();
} else {
myText_text.text = 'error loading xml';
}
}
myXml = new XML();
myXml.ignoreWhite = true;
myXml.onLoad = this.xmlLoaded;
myXml.load('test.xml');
Rely on hack
function xmlLoaded(success){
if (success){
this._parent.myText_txt.text += myXml.toString();
} else {
this._parent.myText_text.text = 'error parsing xml';
}
}
myXml = new XML();
myXml.ignoreWhite = true;
myXml._parent = this;
myXml.onLoad = xmlLoaded;
myXml.load('menu.xml');
In Delegate we trust
import mx.utils.Delegate;
function xmlLoaded(success){
if (success){
myText_txt.text += myXml.toString();
} else {
myText_text.text = 'error loading xml';
}
}
myXml = new XML();
myXml.ignoreWhite = true;
myXml.onLoad = Delegate.create(this, xmlLoaded);
myXml.load('test.xml');
The examples look quite similiar, but if you have run across this problem before you will know how much of a difference using the Delegate will make. Hope you find this useful.
Oct 26, 2005 at 10:14 PM
The Delegate class is great, I don't think a day goes by when I don't use it at least once.
Something that annoyed me at first was the inability to pass arguments through to the function you are targeting. After some playing around a figured out a work around.
Let's pretend we're in a loop and we need to pass through what button called our function, maybe we want to disable it.
Now I know this is a useless example because all of the buttons would eventually be disabled. I just wanted to show you how you can pass through arguments using the delegate class. Hope this helps.
Happy Delegating.
Oct 27, 2005 at 8:44 AM
You can also access the object the initiated the event through the event argument that is normally passed to any event handlers. The event argument is an object that at minimum consists of two properties:
- type: the event type
- target: the object that dispatched the event, in Scott's example the button mc's.
May 11, 2008 at 10:12 PM
Very good article