howtodothis
howtodothis

Reputation: 1295

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
    }

}());

Upvotes: 5

Views: 8212

Answers (2)

Wayne
Wayne

Reputation: 60414

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

Upvotes: 8

Domenic
Domenic

Reputation: 112827

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.

Upvotes: 3

Related Questions