I\'m dealing with a problem about an Ajax callback inside of an Object. Please consider this code :
Search.prototype =
{
ask : function( query )
{
You can use the ES5 .bind function to set this
correctly:
$.ajax(...).done(this.loadResults.bind(this));
(use the shim at the above link, or the jQuery $.proxy
equivalent on older browsers).
Alternatively, add context: this
to the $.ajax
options:
$.ajax({
...,
context: this
}).done(this.loadResults);
Note that in either case you will override jQuery's default behaviour of passing the ajax option object in this
.
p.s. it's also good practise to return
the result of the $.ajax()
chain so that the user of your object can chain additional callbacks (e.g. a .fail
handler) to it.
There are several ways to do this.
You can set the context
setting for the ajax options:
context
setting$.ajax({
context: this
.done(function (res) {
}.bind(this));
However, this is not as widely supported as...
Created for this purpose.
.done($.proxy(function (res) {
}, this);
var self = this;
$.ajax({
/* snip */
.done(function (res) {
self.loadResults(res);
This is commonly done in JavaScript to give access to this
in lower scopes.
$.ajax({
/* snip */
.then(res => this.loadResults(res));
You can use the $.ajax() context
object here like:
$.ajax({
url : 'http://api.deezer.com/search/track/',
context: this,
...
}).done(function (res) {
this.loadResults( res );
});