Reputation: 10775
I'm having trouble figuring out how to correctly reference the 'right' 'this' in a jquery ajax callback.
I have a javascript class where I define the callback:
Foo.prototype.onCallback = function(response) {
// 'this' should refer to an instance of foo in both the following cases
this.bar(...)
this.hello(...)
}
outside of the class I have:
foo1 = new Foo()
myCallback = foo1.onCallback;
$.ajax({
...
success: function(response) {myCallback(response); ... }
});
Right now I believe 'this' within foo1.onCallback is referring to the html element the ajax call is attached to. How do I ensure that 'this' refers to foo1? Is there a better way to do this?
Upvotes: 3
Views: 1779
Reputation:
You could use the context
property of $.ajax
:
var foo1 = new Foo();
$.ajax({
context: foo1,
success: function(response) { this.onCallback(response); }
});
...which causes this
in the callback to reference your Foo
object.
Upvotes: 4
Reputation: 339985
You can't do that.
You must either write:
$.ajax({
...
success: function(response) { foo1.onCallback(response); ... }
});
or this:
myCallback = foo1.onCallback.bind(foo1);
Note that Function.bind()
requires ECMAScript 5.
Upvotes: 2
Reputation: 11351
You could simply add the statement alert(this);
to see the if it is foo1.
Upvotes: -1
Reputation: 340953
Use the following idiom:
myCallback = foo1.onCallback.bind(foo1);
In fact you should take advantage of first-class function support in JavaScript even further:
foo1 = new Foo()
$.ajax({
...
success: foo1.myCallback.bind(foo1)
});
Upvotes: 1