Call back function using `this` in Jquery get()

175 Views Asked by At

I want to use this keyword in the callbacks of $.get(). My code structure is

var myObject = {
  get: function() {
    $.get(server,data,function(data,status) {
      this.callback();
    });
  },
  callback: function() {

  }
}

I don't want to use myObject.callback(). Is there any way to accomplish using this.callback()?

2

There are 2 best solutions below

2
nnnnnn On

You can .bind() the value of this to your callback function before passing it to $.get():

var myObject = {
  get: function() {
    $.get(server, data, function(data, status) {
      this.callback();
    }.bind(this));
  }
  callback: function {
    // do something here
  }
}

Of course, that assumes the value of this within your own myObject.get() function is correct, which it would be if you called it with "dot notation" as myObject.get().

Note also that if the only thing your anonymous function does is call the other function then you can bind the other function directly:

var myObject = {
  get: function() {
    $.get(server, data, this.callback.bind(this));
  }
  callback: function {
    // do something here
  }
}
3
Alexander Nied On

Option #1 -- cache this in a variable (_this):

var myObject = {
    get: function() {
        var _this = this;
        $.get(server, data, function(data, status) {
            _this.callback(); // this keyword refers to Window obj not myObject
        });
    }
    callback: function {
        // do something here
    }
}    

Option #2 -- use jQuery's .proxy method:

var myObject = {
    get: function() {
        $.get(server, data, $.proxy(function(data, status) {
            _this.callback(); // this keyword refers to Window obj not myObject
        }), this);

    }
    callback: function {
        // do something here
    }
}

(Edited-- thanks nnnnnn)