szurubooru/public_html/js/DI.js

68 lines
1.6 KiB
JavaScript
Raw Normal View History

2014-08-31 23:22:56 +02:00
var App = App || {};
App.DI = (function() {
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
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);
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) {
var deps = [];
var depKeys = getFunctionParameterNames(objectIntializer);
for (var i = 0; i < depKeys.length; i ++) {
deps[i] = get(depKeys[i]);
}
return deps;
}
function register(key, objectInitializer) {
factories[key] = {initializer: objectInitializer, singleton: false};
2014-09-08 22:02:28 +02:00
}
2014-08-31 23:22:56 +02:00
function registerSingleton(key, objectInitializer) {
factories[key] = {initializer: objectInitializer, singleton: true};
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
function getFunctionParameterNames(func) {
var fnStr = func.toString().replace(STRIP_COMMENTS, '');
var result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
if (result === null) {
result = [];
}
return result;
}
return {
get: get,
register: register,
registerManual: registerManual,
registerSingleton: registerSingleton,
};
})();