RequireJS and JS Module Pattern
javascript, requirejs
Solution
You can build up your module tree like this with require.js.
// in main.js
require.config({/*...*/});
require(
['app'],
function (app) {
// build up a globally accessible module tree
window.app = app;
var foo = window.app.moduleName.init(); // returns "foo"
}
);
// in app.js
define(
['moduleName'],
function(moduleName){
return {
moduleName: moduleName;
}
}
);
// in moduleName.js
define(function(){
// private property
var someProp = "foo";
return {
// public method
init: function () {
return someProp;
}
}
});
However, with require.js you can build up your app without a global module tree like this... even if you easily can. You can access all parts of your module individually just be requiring them. Whatever you return in the define/require callback will be stored as a reference by require.js. That's something important to know. So it's possible to include a script twice in your application and have the same object or instance. For example if you include a module like this
// in SomeClass.js
define(function () {
function SomeClass() {
this.myValue = true;
}
return new SomeClass();
});
// app.js
define(
['SomeClass', 'someComponent'],
function (SomeClass, someComponent) {
return {
init: function () {
SomeClass.myValue = false;
someComponent.returnClassValue(); // logs false
}
};
}
);
// someComponent.js
define(
['SomeClass'],
function (SomeClass) {
return {
returnClassValue: function () {
console.log(SomeClass.myValue); // false
}
};
}
);
The value of SomeClass.myValue will be the same in all including modules...
Problem
I currently working on a Javascript application that's using multiple javascript file with a "module pattern". Like so: ``` var app = app || {}; app.moduleName = app.moduleName || {}; app.moduleName = function () { // private property var someProp = null; return { // public method init: function () { return "foo"; } }; }(); ``` The reason why im using this is to structurize my code. I can call a method or property by just calling app.moduleName.init() for example. One downside of this is that I must include lots of `<script src="app.moduleName.js">`.. etc in my HTML. To solve this problem, I came across RequireJS, I read the documentation. But I'm not quite sure how to merge this in my existing structure, without adding bunch of code to the existing javascript files. Does somebody have any suggestion how to accomplish this?