Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript module pattern / organization / sub-modules

  1. I would like to know what's the difference (advantages/disadvantages) between the following patterns.
  2. How can I create sub modules based on the module pattern?

My goal is to have my js organized into multiple files that are lazy loaded but have one namespace.

For example:

SO.global (global.js) SO.global.registration (registration.js) <- load

var SO = function(){

    var CONSTANT = 'Z';

    function createX(){
      alert("create X");
    }

    function getY(){
       alert("get Y");
    }
    return{
      create:createX,
      get:getY
    }
}();

//SO.createX(); 
//SO.getY();

VS.

var SO = (function() {

    var CONSTANT = 'Z';

    function createX(){
      alert("create X");
    }

    function getY(){
       alert("get Y");
    }

    return {
      create:createX,
      get:getY
    }

} ());
like image 249
Eeyore Avatar asked Nov 04 '10 20:11

Eeyore


1 Answers

Have you considered Require.JS? It attempts to provide the following solution:

  • Some sort of #include/import/require
  • ability to load nested dependencies
  • ease of use for developer but then backed by an optimization tool that helps deployment

Require.JS implements the Module/Asynchronous Definition spec defined by Common.JS

like image 171
jaaronfarr Avatar answered Oct 05 '22 10:10

jaaronfarr