Skip to content

Instantly share code, notes, and snippets.

@andrewchilds
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewchilds/ffcae28b2b01c5fbbb12 to your computer and use it in GitHub Desktop.
Save andrewchilds/ffcae28b2b01c5fbbb12 to your computer and use it in GitHub Desktop.
A Better JavaScript Module Pattern
var App = (function () {
var pub = {};
pub.module = function (ns, fn) {
var context = pub;
var modules = ns.split('.');
var last = modules.pop();
for (var i = 0; i < modules.length; i++) {
context[modules[i]] = context[modules[i]] || {};
context = context[modules[i]];
}
context[last] = context[last] || {};
var result = fn(context[last]);
if (typeof result !== 'undefined') {
context[last] = result;
}
};
return pub;
}());
App.module('Controller.Foo', function (exports) {
var myPrivateArray = [];
exports.myFunction = function () {
App.Model.Foo.myFunction();
};
exports.myOtherFunction = function () {
};
});
App.module('Model.Foo', function (exports) {
exports = Collectionize('Foo');
exports.myFunction = function () {
};
exports.myOtherFunction = function () {
};
return exports;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment