javascript - Revealing Module Pattern - Global variables / Init function -


i want rid of unstructured way of writing js , red lot "revealing module pattern" lately. @ least me seems pretty usefull, haven't found answers of questions yet. let's have different modules in our js, in case "site" , "nav". "nav" module has private functions in , public ones later on. what's best way of calling init function in modules. thought of creating public function them , calling them module.init();. me seems bad practice , haven't seen anywhere before.

$(function () {     var site = (function () {         var              module = {},             privatevar = 3; // private variable          function privatefunction() { // private function             // code here         }          module.init = function () {            // global init function         };                  return module;     }());      var nav = (function () {         var              module = {},             navopen = false; // private variable          function open() { // private function             // code here         }         function close() { // private function             // code here         }          module.init = function () {                                 // event handlers open , close functions etc.         };                  return module;     }());      nav.init();     site.init();  }); 

another question, didn't find in of articles red how define global variable (like body), need in of modules (adding classes or something). let's need access body (like in jquery $("body")) in both "nav" , "site" module. better that:

$(function () {     var site = (function () {         var              module = {},             body = $("body"); // creating "body" variable in every module          // .. module code         return module;     }());      var nav = (function () {         var              module = {},             body = $("body"); // , again in module          // module code                return module;     }());  }); 

or have @ top of js file

$(function () {     var         body = $("body");      var site = (function () {         // module code     }());      var nav = (function () {         // module code     }()); 

or there better way / improve code in general? in advance help.

you'll access of body variables closure, example here.

so, don't need declare body variable inside functions.

for constructor issue, have one, function use declare object, see example detailed example


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -