Skip to content

Instantly share code, notes, and snippets.

@mjpitz
Last active August 29, 2015 14:11
Show Gist options
  • Save mjpitz/23dd44e6349a1d3864ad to your computer and use it in GitHub Desktop.
Save mjpitz/23dd44e6349a1d3864ad to your computer and use it in GitHub Desktop.
Simple dependency injection using reflection
(function($, undefined) {
var dependencies = {},
instances = {};
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function stripComments(functionString) {
return functionString.replace(STRIP_COMMENTS, '');
}
var FN_NEW_LINE_REPLACE = /[\s\r\n]+/;
function oneline(functionString) {
return functionString.replace(FN_NEW_LINE_REPLACE, '');
}
var STRIP_WHITESPACE = /[\s\t]/g;
function trimWhitespace(functionString) {
return functionString.replace(STRIP_WHITESPACE, '');
}
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
function parseArgs(functionString) {
return functionString.match(FN_ARGS)[1];
}
var FN_ARG_SPLIT = /,/;
function getArgs(functionString) {
if (functionString) {
return functionString.split(FN_ARG_SPLIT);
} else {
return [];
}
}
/**
* [$injector description]
* @type {[type]}
*/
$.injector = {
/**
* [annotate description]
* @param {[type]} constructorFn [description]
* @return {[type]} [description]
*/
annotate: function(constructorFn) {
var sanitizedFn = stripComments(constructorFn.toString());
var onelinedFn = oneline(sanitizedFn);
var condensedFn = trimWhitespace(onelinedFn);
var argString = parseArgs(condensedFn);
var args = getArgs(argString);
constructorFn.inject_ = args;
},
/**
* [provide description]
* @param {[type]} name [description]
* @param {[type]} constructorFn [description]
* @return {[type]} [description]
*/
provide: function(name, constructorFn) {
this.annotate(constructorFn);
dependencies[name] = constructorFn;
return constructorFn;
},
/**
* [get description]
* @param {[type]} name [description]
* @return {[type]} [description]
*/
get: function(name) {
var instance = instances[name];
if (instance) {
return instance;
}
var constructorFn = dependencies[name];
if (constructorFn) {
var deps = [];
for (var a = 0; a < constructorFn.inject_.length; a++) {
var dependency = this.get(constructorFn.inject_[a]);
deps.push(dependency);
}
var fn = new constructorFn();
constructorFn.apply(fn, deps);
instances[name] = fn;
return fn;
} else {
throw new Error('Dependency [' + name + '] not registered in graph.');
}
}
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment