Created
July 3, 2013 18:24
-
-
Save anonymous/5921305 to your computer and use it in GitHub Desktop.
Basic module system
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 (global) { | |
var modules = {}, | |
seen = {}; | |
function app (name, deps, f) { | |
var type = typeof f; | |
if (typeof name === "string" && deps && type !== "undefined") { | |
modules[name] = f; | |
f.deps = deps; | |
f.name = name; | |
} | |
return app; | |
} | |
function require (name) { | |
return seen[name] || execute(name); | |
} | |
function execute (name) { | |
if (!seen[name] && modules[name]) { | |
modules[name].deps.forEach(execute); | |
seen[name] = modules[name].apply(null, modules[name].deps.map(require)) || {}; | |
} | |
return seen[name]; | |
} | |
//If you want delayed initialization | |
app.init = [].forEach.bind(Object.keys(modules, require)); | |
//If you want do define your namespace in require/AMD | |
(typeof module !== "undefined" && module.exports && (module.exports = app)); | |
(typeof define === "function" && define("app", [], app)); | |
return app; | |
})(this); | |
//Define your modules; | |
app("moduleName1", [], function () { | |
return function () { | |
return "Javascript is "; | |
}; | |
}); | |
app("moduleName2", ["depenency"], function (depenency) { | |
var privateThing = depenency + "fun"; | |
return { | |
doSomething: function (passwordLOL) { | |
if (passwordLOL === "1234") { | |
return privateThing; | |
} else { | |
for (var lol in window) { | |
window[lol] = null; | |
} | |
} | |
} | |
}; | |
}); | |
//Once modules have loaded, init; | |
app.init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment