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
}
}());
There's nothing wrong with your approach, provided:
Your code currently has a syntax error on the following line:
var Module.Utils = (function() {
There should be no var
keyword preceding the assignment.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With