Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Module Pattern - How to Create Sub Modules

How do I access/create a sub module based on the module pattern?

I would like to have the ability to access methods from sub modules in my Modules.js main file.

Module.js

var Module = (function() {

    function A(){
      console.log("Module: A");
      B();
    };

    function B(){
       console.log("Module: B");
       Module.Utils.C(); /* Here is the problem */
    };

    return {
      A:A,
      B:B
    }

} ());

$(function() {
    Module.A();
});

Module.Utils.js

var Module = Module ? Module : {};

Module.Utils = (function() {

    var settings = {
        x : 1,
        y : 2
    };

    function C(){
      console.log("Module.Utils: C");
    };

    function D(){
       console.log("Module.Utils: D");
    };

    return {
      C:C,
      D:D
    }

}());
like image 574
howtodothis Avatar asked Oct 19 '11 16:10

howtodothis


2 Answers

There's nothing wrong with your approach, provided:

  • You load the sub-module script after the module script
  • You do not attempt to access the sub-module script before it is loaded
  • You're OK with making your primary module dependent on the existence of the sub-module. (I'm not so sure this is a good idea.)

Side-issue

Your code currently has a syntax error on the following line:

var Module.Utils = (function() {

There should be no var keyword preceding the assignment.

Example Code

Here's a simplified version of your code -- stripped to show only the methods I'm invoking -- that demonstrates that your approach works:

var Module = (function() {

    function B() {
        console.log("Module: B");
        Module.Utils.C(); /* accessing submodule public methods */
    };

    return {
        B: B
    };

})();

var Module = Module || {};

Module.Utils = (function() {

    function C() {
        console.log("Module.Utils: C");
    };

    return {
        C: C
    }

})();

Module.B();

Output:

Module: B
Module.Utils: C
like image 135
Wayne Avatar answered Oct 04 '22 22:10

Wayne


You should look into using an actual module framework like RequireJS.

A "submodule" would then just be a module located at module/utils, and your module module would require it as a dependency, which RequireJS would take care of resolving for you.

like image 35
Domenic Avatar answered Oct 04 '22 23:10

Domenic