Skip to content

Instantly share code, notes, and snippets.

@liammclennan
Created May 15, 2012 11:44
Show Gist options
  • Save liammclennan/2701105 to your computer and use it in GitHub Desktop.
Save liammclennan/2701105 to your computer and use it in GitHub Desktop.
JavaScript IoC
var define = function define(name, dependencies, moduleFactory) {
window.modules = window.modules || {};
window.modules[name] = {
'moduleFactory': moduleFactory || dependencies,
'dependencies': typeof(moduleFactory) == 'undefined' ? [] : dependencies
};
};
var require = function require(name) {
var module = window.modules[name],
deps = [];
for (var i = 0; i < module.dependencies.length; i++) {
deps.push(require(module.dependencies[i]));
}
return module.moduleFactory.apply(this, deps);
};
// define a module 'B' that depends on module 'A'
define('b', ['a'], function (a) {
return {
report: function () {
a.report();
console.log('B');
}
};
});
// define a module 'A'
define('a', function () {
return {
report: function () {console.log('A');}
};
});
var a = require('a');
a.report(); // "A"
var b = require('b');
b.report(); // "AB"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment