-2

Given class functions

game.PlayScreen = me.ScreenObject.extend({  

    onResetEvent: function() {
        this.setAll(); //calls setAll(), which calls setGlobals()
        this.saveNextLevelData(this.setAll);
    },

    saveNextLevelData : function (callback) {
        $.get("./php/CRUD.php", {},
            function (returned_data) {
                callback(); //however, the callback of setAll throws 
                           `undefined is not a function` error
            }
    },

    setAll : function () {
         log("setAll called");
         this.setGlobals();
    },

    setGlobals : function () {
         log("setGlobals called");
    }
});

Basically, I'm confused on how this context is lost when you call a callback function.

In the above code,

  • Works: this.setAll() called directly from onResetEvent outputs "setAll called" and "setGlobals called"

  • Breaks: callback() calling this.setAll() from $.get outputs "setAll called" but this.setGlobals(); breaks... I think due to lost this context... It outputs Uncaught TypeError: undefined is not a function

I'm trying to follow the context of this when you call a callback function which contains a function belonging to the parent object (this, in this case). If I want to call this.setGlobals() from a callback of this.setAll(), where exactly do I need to do the bind?

Thanks

user3871
  • 12,432
  • 33
  • 128
  • 268
  • You asked [nearly the same question](http://stackoverflow.com/questions/22364352/confused-on-prototype-bindings-this-statement) two months ago. – cookie monster May 21 '14 at 00:05

1 Answers1

1

I think it is best to pass the context from the caller part, it can be done using $.proxy()/Function.bind() so

this.saveNextLevelData($.proxy(this.setAll, this));

Another solution will be is to pass the current object as the context to the callback from the ajax callback, the problem is by default this in the callback will refer to the ajax settings object. so

saveNextLevelData : function (callback) {
    var self = this;
    $.get("./php/CRUD.php", {},
        function (returned_data) {
            callback.call(self);
        }
},
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531