JavaScript module template - creating helper modules

How do I get / create an add-on module based on a module template?

I would like to be able to access methods from additional modules in the main Modules.js 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 } } ()); 
+4
source share
2 answers

There is nothing wrong with your approach if:

  • Download the script submodule after the script module
  • You are not trying to access the script submodule before loading it
  • You are fine so that your core module depends on the existence of a submodule. (I'm not sure this is a good idea.)

Side question

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

 var Module.Utils = (function() { 

There should not be a var keyword preceding the assignment.

Code example

Here's a simplified version of your code - disabled to show only the methods that I call - which demonstrates that your approach works:

 var Module = (function() { function B() { console.log("Module: B"); Module.Utils.C(); /* Here is the problem */ }; 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 
+7
source

You should study the real structure of the module, for example RequireJS .

A โ€œsubmoduleโ€ would then be just a module located in module/utils , and your module module would require it as a dependency, which RequireJS will take care of for you to resolve.

+3
source

All Articles