Need Flex Migration Help?
- Adobe ends Flash player support in 2020
- Flex apps will no longer function
- We can help migrate your app
Most Flex developers are aware of the Delegate class, and its static create method, which lets you have a method of one object fire in the scope of another object. Its a quick, clean and elegant solution to one of the more painful challenges of Flash development, that is, methods firing in a scope other than the scope which was expected.
What many don’t realize is this same Delegate class is available to flash developers, so long as you are running the Flash Studio 7.2 update. Lets look at a simple example where this can be helpful.
class XMLDataLoader {
var xmlObj:XML;
var url:String=”http://jeff.mxdj.com/index.rss”;
function XMLDataLoader(){
xmlObj = new XML();
xmlObj.ignoreWhite = true;
xmlObj.load(url);
xmlObj.onLoad = parseData;
}
function parseData(success:Boolean){
trace(this);
}
function toString():String{
return “[XMLDataLoader]”
}
}
As this class is instantiated, it creates an xml object, loads a file. When its done, the parseData method is fired. Now, here is the Flash oddity. The trace statement in parse data, rather than returning “[XMLDataLoader]”, returns the xml object. Whats happened is that the method is fired in the scope of the xml object. This isn’t actually a bug, those of us who have been working with flash for a while expect this behavior.
Now for the good news, using the Delegate class, we can make this behave as expected. Try this instead:
class XMLDataLoader {
var xmlObj:XML;
var url:String=”http://jeff.mxdj.com/index.rss”;
function XMLDataLoader(){
xmlObj = new XML();
xmlObj.ignoreWhite = true;
xmlObj.load(url);
xmlObj.onLoad = mx.utils.Delegate.create(this,parseData);
}
function parseData(success:Boolean){
trace(this);
}
function toString():String{
return “[XMLDataLoader]”;
}
}
Note, that the xmlObj.onLoad is now using the Delegate.create to assign parseData as the event handler. This time, as the xml is loaded, the parseData method is fired in the scope of the XMLDataLoader class (the trace statement properly fires the classes toString() method, and returns “[XMLDataLoader]”
These days, I find myself using Delegate.create any time I reference an event Flashes built in classes.