2014-08-31 23:22:56 +02:00
|
|
|
var App = App || {};
|
|
|
|
|
|
|
|
App.DI = (function() {
|
|
|
|
|
|
|
|
var factories = {};
|
|
|
|
var instances = {};
|
|
|
|
|
|
|
|
function get(key) {
|
|
|
|
var instance = instances[key];
|
|
|
|
if (!instance) {
|
|
|
|
var factory = factories[key];
|
2014-09-08 22:02:28 +02:00
|
|
|
if (!factory) {
|
2014-08-31 23:22:56 +02:00
|
|
|
throw new Error('Unregistered key: ' + key);
|
2014-09-08 22:02:28 +02:00
|
|
|
}
|
2014-08-31 23:22:56 +02:00
|
|
|
var objectInitializer = factory.initializer;
|
|
|
|
var singleton = factory.singleton;
|
2014-09-11 12:33:44 +02:00
|
|
|
var deps = resolveDependencies(objectInitializer, factory.dependencies);
|
2014-09-08 22:02:28 +02:00
|
|
|
instance = {};
|
2014-08-31 23:22:56 +02:00
|
|
|
instance = objectInitializer.apply(instance, deps);
|
2014-09-08 22:02:28 +02:00
|
|
|
if (singleton) {
|
2014-08-31 23:22:56 +02:00
|
|
|
instances[key] = instance;
|
2014-09-08 22:02:28 +02:00
|
|
|
}
|
2014-08-31 23:22:56 +02:00
|
|
|
}
|
|
|
|
return instance;
|
|
|
|
}
|
|
|
|
|
2014-09-11 12:33:44 +02:00
|
|
|
function resolveDependencies(objectIntializer, depKeys) {
|
2014-08-31 23:22:56 +02:00
|
|
|
var deps = [];
|
|
|
|
for (var i = 0; i < depKeys.length; i ++) {
|
|
|
|
deps[i] = get(depKeys[i]);
|
|
|
|
}
|
|
|
|
return deps;
|
|
|
|
}
|
|
|
|
|
2014-09-11 12:33:44 +02:00
|
|
|
function register(key, dependencies, objectInitializer) {
|
|
|
|
factories[key] = {initializer: objectInitializer, singleton: false, dependencies: dependencies};
|
2014-09-08 22:02:28 +02:00
|
|
|
}
|
2014-08-31 23:22:56 +02:00
|
|
|
|
2014-09-11 12:33:44 +02:00
|
|
|
function registerSingleton(key, dependencies, objectInitializer) {
|
|
|
|
factories[key] = {initializer: objectInitializer, singleton: true, dependencies: dependencies};
|
2014-09-08 22:02:28 +02:00
|
|
|
}
|
2014-08-31 23:22:56 +02:00
|
|
|
|
|
|
|
function registerManual(key, objectInitializer) {
|
|
|
|
instances[key] = objectInitializer();
|
2014-09-08 22:02:28 +02:00
|
|
|
}
|
2014-08-31 23:22:56 +02:00
|
|
|
|
|
|
|
return {
|
|
|
|
get: get,
|
|
|
|
register: register,
|
|
|
|
registerManual: registerManual,
|
|
|
|
registerSingleton: registerSingleton,
|
|
|
|
};
|
|
|
|
|
|
|
|
})();
|