samedi 13 août 2016

Javscript modular design pattern - which is better: self-invoking function, or constructor?

In my quest to write better, tighter, more secure code I am excited to be adopting a more modular pattern in my Javascript. However in my self-education on the subject, I am seeing there are different ways to do it. It seems that the two most common would be the self-invoking function pattern (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();       // Outputs: 'contents'
console.log(HTMLChanger.contents);  // undefined

or, from this other article, the constructor pattern:

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) {
    // $.ajax or something
    // using numToGet as param
  }

};

And I am sure a host of others (some described in the first article) - which pattern is better, and/or more common? If I were to choose a default go-to (unless I had a specific reason to choose another pattern) which should it be, and why?

Aucun commentaire:

Enregistrer un commentaire