public
Created

Modular javascript

  • Download Gist
extending_modules.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
// 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();
index.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<!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>
module_a.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14
(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;
})();
module_b.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
(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;
})();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.