Javascript - How To Bind 'this' Inside An Ajax Call To The Object Literal
I have an object literal router, containing an ajax call. I want to call other functions this.printMovies() inside the ajax call but this refer to the ajax object. How do I escape
Solution 1:
Pass context
option to ajax:
$.ajax({
context: this,
/* other options */
}
Now inside ajax callbacks, this
will refer to router
object.
Solution 2:
Here in this case, the function getData
holds the context of it's parent object in this
keyword. So what you can do is, store the reference of this
in some variable and use it later. like:
var router = {
//...
init : function() {
this.getData("api/movies", "movies", callback);
},
getData : function (url, htmlType, callback) {
var mainObj = this; // line to be noticed
$.ajax({
url: url,
dataType: 'json',
success: function (response) {
if (response && response.length > 0) {
// parent object to be used
mainObj.printMovies(response, callback); //'this' refers to ajax
}
},
error: function (response) { console.log("Error:" + response); }
});
},
printMovies : function(){
}
}
Solution 3:
Bind the entire success call back with bind it will work:
(function (response) {
if (response && response.length > 0) {
this.printMovies(response, callback); }
}).bind(this)
Solution 4:
A very common approach is to assign this
to a local variable at the beginning of your function.
var self = this;
Then inside your callback use self
instead of this
:
self.printMovies(response, callback);
Solution 5:
You can use the new ES6 arrow functions, or bind.
You might have to do this on your success or getData function
getData : function (url, htmlType, callback) {
...
}.bind(this),
Post a Comment for "Javascript - How To Bind 'this' Inside An Ajax Call To The Object Literal"