javascript - Modular pattern with DOM elements -


i trying structure javascript using module pattern.

var apptest = {       settings: {          date    : $(".date")     },       init: function() {         s = this.settings;          this.setdate();     },      setdate: function() {         var monthnames = [ "january", "february", "march", "april", "may", "june","july", "august", "september", "october", "november", "december" ];         var dt = new date();         s.date.html(dt.getdate()+" "+monthnames[dt.getmonth()]+" "+dt.getfullyear());         //$(".date").html(dt.getdate()+" "+monthnames[dt.getmonth()]+" "+dt.getfullyear());     }  };   $(function(){     apptest.init();  }); 

right now, dom element class .date doesn't updated new date. if uncomment line commented, works fine.

i still trying find way around javascript.

some problems in module :

  • it uses global variable, s, without declaring , risks of name collision. should embed it
  • you expose settings
  • you use dom before it's ready
  • you call setdate on object doesn't have function

you fix problems :

var apptest = (function(){      var monthnames = [ "january", "february", "march", "april", "may", "june","july", "august", "september", "october", "november", "december" ];     var settings = {}; // private (not visible outside module)     var module = {};     module.init = function() {         settings.date = $(".date");         module.setdate();     };     module.setdate = function() {         var dt = new date();         settings.date.html(dt.getdate()+" "+monthnames[dt.getmonth()]+" "+dt.getfullyear());     };     return module; })();   $(function(){     apptest.init();  }); 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -