szurubooru/public_html/js/DI.js

55 lines
1.3 KiB
JavaScript
Raw Normal View History

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;
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;
}
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;
}
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
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,
};
})();