Skip to content

Instantly share code, notes, and snippets.

@marcofiset
Last active August 29, 2015 14:08
Show Gist options
  • Save marcofiset/4de8e6dae8026fbbed74 to your computer and use it in GitHub Desktop.
Save marcofiset/4de8e6dae8026fbbed74 to your computer and use it in GitHub Desktop.
Simple IoC container in javascript using function reference as types.
App = (function() {
var bindings = {};
return {
make: make,
bind: bind
};
function bind(type, object) {
bindings[type] = object;
}
function make(type) {
if (bindings[type])
return resolveBinding(bindings[type]);
var deps = type.$inject || [];
var args = deps.map(make);
return construct(type, args);
}
function resolveBinding(obj) {
if (typeof obj === 'function')
return make(obj);
return obj;
}
// This is how you use .apply() with the "new" operator in Javascript
// http://stackoverflow.com/questions/1606797/use-of-apply-with-new-operator-is-this-possible
function construct(constructor, args) {
function F() {
return constructor.apply(this, args);
}
F.prototype = constructor.prototype;
return new F();
}
})();
function Logger() {}
function ConsoleLogger() {
this.log = function(msg) {
console.log(msg);
}
}
function ItemRepository() {};
LoggingItemRepository.$inject = [Logger];
function LoggingItemRepository(log) {
this.get = function(id) {
log.log('getting item with id' + id);
};
}
ItemService.$inject = [ItemRepository];
function ItemService(repo) {
this.doIt = function() {
repo.get(12);
};
}
App.bind(Logger, ConsoleLogger);
App.bind(ItemRepository, LoggingItemRepository);
var service = App.make(ItemService);
service.doIt();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment