In my quest to write better, tougher, more secure code, I am very happy to accept a more modular template in my Javascript. However, in my self-education on this issue, I see that there are different ways to do this. It seems that the two most common would be self-starting function templates ( from this article ):
var HTMLChanger = (function() {
var contents = 'contents'
var changeHTML = function() {
var element = document.getElementById('attribute-to-change');
element.innerHTML = contents;
}
return {
callChangeHTML: function() {
changeHTML();
console.log(contents);
}
};
})();
HTMLChanger.callChangeHTML();
console.log(HTMLChanger.contents);
or from this other article , the object approach template:
var s,
NewsWidget = {
settings: {
numArticles: 5,
articleList: $("#article-list"),
moreButton: $("#more-button")
},
init: function() {
s = this.settings;
this.bindUIActions();
},
bindUIActions: function() {
s.moreButton.on("click", function() {
NewsWidget.getMoreArticles(s.numArticles);
});
},
getMoreArticles: function(numToGet) {
}
};
And I'm sure that many others (some of which are described in the first article) - which template is better and / or more general? If I were to choose the default option (unless I had a specific reason to choose a different template), and this should be and why?
?