Created
May 15, 2012 11:44
-
-
Save liammclennan/2701105 to your computer and use it in GitHub Desktop.
JavaScript IoC
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 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