How to call a method inside a javascript object
Solution 1
You want to store the this
binding in a variable.
drawMap: function() {
var _this = this;
$.getJSON('/reports.json', function(data) {
_this.plotMapPoints(data);
});
}
Solution 2
Late answer, but jQuery has a method called jQuery.proxy()
that is made for this purpose. You pass it the function along with the value of this
you want to retain, and it will return a function that ensures this
is correct.
This way you don't need to define a variable.
drawMap: function() {
$.getJSON('/reports.json', $.proxy(function(data) {
this.plotMapPoints(data);
}, this));
}
Solution 3
You need to use a variable reference to this
outside the getJSON
function. getJSON
sets the context of the callback within jquery.
Like this:
var self = this;
$.getJSON('/reports.json', function(data) {
self.plotMapPoints(data);
});
joeellis
Updated on June 20, 2022Comments
-
joeellis about 2 years
I'm just learning about how to best organize my javascript code, and I had a question regarding this small piece of code I wrote:
var reportsControllerIndex = { plotMapPoints: function(data) { //plots points }, drawMap: function() { $.getJSON('/reports.json', function(data) { reportsControllerIndex.plotMapPoints(data); }); }, run: function() { reportsControllerIndex.drawMap(); } };
The question is regarding calling another function of reportsControllerIndex from within the reportsControllerIndex object. I had first tried the following piece of code for the run function:
run: function() { this.drawMap(); }
which worked perfectly. However, I then quickly found doing this for the drawMap function:
drawMap: function() { $.getJSON('/reports.json', function(data) { this.plotMapPoints(data); }); }
does not work, since "this" would now refer to the callback function of the getJSON call.
My solution was to just place reportsControllerIndex in front of all of the methods I want to call, but I was curious: is there a more relative way for calling functions within an overall object like this (much like you'd do with a class in a standard OO language)? Or am I forced to do it as I am currently, just calling the methods through the name of the object?
-
joeellis over 13 yearsAhh, that makes a lot of sense, thanks! Would you say that overall this practice is used in more javascript code than Josiah's suggestion below? I like the idea of using "self" better just for my own OO mindset, but I'd rather follow standard practices in the JS world where I can.
-
ChaosPandion over 13 years@japancheese - I don't believe there is a convention so you should use what you like. Just remember to keep the name reasonable.