Reputation: 11755
So I have a class with a few methods, one of the methods is used as a callback. But depending on how I declare the callback, the pointer of this
has a switched context. I'm wondering how to make this work where the pointer of this
is the object itself.
An example of my issue:
return {
init: function(){
this.starting = 0;
var _this = this;
$.ajax({/* some params */})
.done(function(response){
_this.addOne(); // here the context is fine, one gets added
})
.fail( _this.subtractOne ); // the callback points to the function below,
// but 'this' doesn't point to the same thing
},
addOne: function(){
this.starting++;
},
subtractOne: function(){
this.starting--;
}
}
How can I use the notation that .fail
uses, but still subtract correctly?
Upvotes: 1
Views: 54
Reputation: 174957
Because this
is determined by how the function is called, rather than how it's written.
jQuery calls its callback functions with this
bound to whatever makes sense to jQuery at the moment (for example, for event handlers, this
is bound to the DOM element that triggered the event).
Because of that, the this
in this.starting--
isn't what you think it is.
You can force this
to be whatever you want by passing the result of .bind()
on your function, like so:
.fail(_this.substractOne.bind(_this));
Upvotes: 3
Reputation: 36438
bind()
will make sure the call is made with a proper this
reference:
.fail( _this.subtractOne.bind( _this ) );
Upvotes: 3