Avinash
Avinash

Reputation: 922

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

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()?

Upvotes: 2

Views: 179

Answers (2)

Alexander Nied
Alexander Nied

Reputation: 13668

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)

Upvotes: 2

nnnnnn
nnnnnn

Reputation: 150080

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
  }
}

Upvotes: 5

Related Questions