Last active
August 29, 2015 14:03
-
-
Save andrewchilds/ffcae28b2b01c5fbbb12 to your computer and use it in GitHub Desktop.
A Better JavaScript Module Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
App.module('Controller.Foo', function (exports) { | |
var myPrivateArray = []; | |
exports.myFunction = function () { | |
App.Model.Foo.myFunction(); | |
}; | |
exports.myOtherFunction = function () { | |
}; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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