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 = {
You can write it likes this:
var reportsControllerIndex = new function () {
var self = this;
self.plotMapPoints = function (data) {
//plots points
},
self.drawMap = function () {
$.getJSON('/reports.json', function (data) {
self.plotMapPoints(data);
});
},
self.run = function () {
self.drawMap();
}
};
This class will works as same as you did, and you can still call the class method by:
reportsControllerIndex.run()
In this paradigm, I defined self
pointing to the class itself, so that you can call self
wherever you want in the class.
Farther, this paradigm can solve the this
problem in the function that you bring as callback to another funciton:
plotMapPoints: function(data) {
console.log(this);
// Need a this referring to the class itself
// It's inconvenient to bring this as parameter
},