...yes is really handy and if you specify whole path (
mx.utils.Delegate.create()) to the class you don't need to import it; only when use
Delagate.create() than you have to import it
(
import mx.utils.Dejagate;)
and with this class I'll try simplify you what's happening:
PHP Code:
class Communicator{
/*
file vars.txt:
--------------------------------------
loadedTestVar=loadedVarIsOk
--------------------------------------
*/
private var dataSet:LoadVars;
private var scopeTest:String;
function Communicator(){
scopeTest = "OK";
}
// --------------------------
// CASE A (with a Delegate)
function getDataV1():Void{
dataSet = new LoadVars();
dataSet.load("vars.txt");
dataSet.onLoad = mx.utils.Delegate.create(this, onDataV1);
// mx.utils.Delegate will return a Function and that
// function will call your function in specified scope
// and when instance of a LoadVars class in some point calls its onLoad(true);
// the scope will not be instance of a LoadVars class but instance of a
// Communicator class (this class)
}
function onDataV1(success:Boolean):Void{
trace("scopeTest = " + scopeTest); // outputs: "OK"
// so onDataV1 is called from an instance of Communicator class
// and you can reach all you instance properties including scopeTest var
// and this will also work
trace("scopeTest = " + this.scopeTest); // outputs: "OK"
// and for reading dataSet
trace("loadedTestVar = " + dataSet.loadedTestVar); // outputs: "loadedVarIsOk"
}
// --------------------------------
// CASE B (with a nested function)
function getDataV2():Void{
dataSet = new LoadVars();
dataSet.load("vars.txt");
// forget this for a moment I will explain later
// (local var will be visible for all nested functions)
var classScopeA = this;
dataSet.onLoad = function(success:Boolean){
trace("scopeTest = " + this.scopeTest); // outputs: ""
trace("scopeTest = " + scopeTest); // also outputs: ""
// that is because "this" is now reference to the dataSet,
// not to the our class instance
// and thats imply this
trace("loadedTestVar = " + this.loadedTestVar); // outputs: "loadedVarIsOk"
// see the difference?
// there are two ways to reach you class frome here now
// solution A.
trace("sol A: scopeTest = " + classScopeA.scopeTest); // outputs: "OK"
// that's because all locally declared var will be visible for this function
// solution B.
trace("sol B: scopeTest = " + arguments.callee.classScopeB.scopeTest); // outputs: "OK"
// arguments is an Array containing all arguments passed to the function
// but also can provide reference to the function it self (arguments.callee)
// and because function is basically an object you can declare vars inside function
// exemple of that is in next line below
}
dataSet.onLoad.classScopeB = this;
}
}
to use it:
PHP Code:
var comm = new Communicator();
comm.getDataV1();
comm.getDataV2();