Last active
August 29, 2015 14:08
-
-
Save marcofiset/4de8e6dae8026fbbed74 to your computer and use it in GitHub Desktop.
Simple IoC container in javascript using function reference as types.
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
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(); | |
} | |
})(); |
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
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