1

I got some methods (methA, methB ...) that need to call the same method methMain in Javascript. This method methMain then need to fetch some data and when it is done do a callback to the method that called it (methA or MethB ...).

I can successfully create a pointer/reference to a method by using what is written here: How can I pass a reference to a function, with parameters?

That solution, and all others I have seen, does not seem to work in the current scope. This code will not work:

function TestStructure() {

    this.gotData = false;

    //define functions
    this.methA = function (parA) { };
    this.methB = function (parb) { };
    this.createFunctionPointer = function (func) { };


    this.createFunctionPointer = function (func /*, 0..n args */) {
        var args = Array.prototype.slice.call(arguments, 1);
        return function () {
            var allArguments = args.concat(Array.prototype.slice.call(arguments));
            return func.apply(this, allArguments);
        };
    };

    this.methA = function (parA) {

        alert('gotData: ' + this.gotData + ', parA: ' + parA);

        if (this.gotData == false) {
            var fp = this.createFunctionPointer(this.methA, parA);
            this.methMain(fp);
            return;
        }

        //...do stuff with data
    }

    this.methB = function (parB) {

        alert('gotData: ' + this.gotData + ', parB: ' + parB);

        if (this.gotData == false) {
            var fp = this.createFunctionPointer(this.methB, parB);
            this.methMain(fp);
            return;
        }

        //...do stuff with data
    }

    this.methMain = function (func) {

        //...get some data with ajax

        this.gotData = true;

        //callback to function passed in as parameter
        func();
    }
}

var t = new TestStructure();
t.methA('test');

When methMain do a callback to func (methA or methB) the variable this.gotData will not be set.

Is there a solution for this problem or do I need to re-think the design? I want to do this to get data with ajax without blocking with async: false.

Community
  • 1
  • 1
AxAn
  • 143
  • 12

1 Answers1

0

I am not 100% sure but I think you can solve your problem by doing

this.createFunctionPointer = function (func /*, 0..n args */) {
    var args = Array.prototype.slice.call(arguments, 1);
    var that = this; //<<< here
    return function () {
        var allArguments = args.concat(Array.prototype.slice.call(arguments));
        return func.apply(that, allArguments);
                   //here ^^^
    };
};

This will cause your partially evaluated function to be called with the same this that created the function pointer. If you want a different scope just change whatever you pass to .apply.

hugomg
  • 68,213
  • 24
  • 160
  • 246
  • Thank you for the input, it now works - which is somewhat embarrassing since I tried what you did before posting here. :-) – AxAn Nov 28 '11 at 12:23