Skip to content

Instantly share code, notes, and snippets.

@dsimard
Created February 10, 2012 16:10
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 dsimard/1790530 to your computer and use it in GitHub Desktop.
Save dsimard/1790530 to your computer and use it in GitHub Desktop.
Modular javascript
// This function is for demo purpose
function addStep(msg) {
$("#steps").append(
$("<li>").text(msg)
);
}
// Here is where I extend all modules
(function() {
// This will contain all properties and functions from all loaded modules
var z = {};
// Check which modules are loaded
addStep("Check which modules are loaded");
for (var module in window.modules) {
if (window.modules.hasOwnProperty(module)) {
addStep("Module '" + module + "' is loaded");
// Load each properties and functions of the module
var props = [];
for (var prop in window.modules[module]){
if (window.modules[module].hasOwnProperty(prop)) {
z[prop] = window.modules[module][prop];
props.push(prop);
}
}
addStep("Added '" + props.join(", ") + "' from module '" + module + "'");
}
}
window.z = z;
})();
// Check if can call A
if (typeof z.callA === 'function') z.callA();
// Check if can call B
if (typeof z.callB === 'function') z.callB();
<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<!-- THIS IS WHERE YOU LOAD SUB MODULES : try to change it -->
<script src="http://raw.github.com/gist/1790530/b3dccf47d684c68b44ef4a6ff7626c170a4a5234/module_a.js"></script>
<script src="https://raw.github.com/gist/1790530/d57483c6bb2932f7810494c3a94c58c5c83ff3e6/module_b.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<h2>Steps</h2>
<ol id="steps">
</ol>
</body>
</html>
(function() {
addStep("Init A");
var a = {
callA: function() {
addStep("This is a call to module A : " + a.propertyFromA);
},
propertyFromA : 'My name is A'
};
// Make sure that window.modules exists
if (typeof window.modules === 'undefined') window.modules = {};
window.modules.a = a;
})();
(function() {
addStep("Init B");
// Here are the properties and functions of module B
var b = {
callB: function() {
addStep("This is a call to module B : " + b.propertyFromB);
},
propertyFromB : 'My name is B'
};
// Make sure that window.modules exists
if (typeof window.modules === 'undefined') window.modules = {};
window.modules.b = b;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment