Skip to content

Instantly share code, notes, and snippets.

@maxdignan
Last active December 2, 2015 19:15
Show Gist options
  • Save maxdignan/a2ea539a18aaec2f3cfb to your computer and use it in GitHub Desktop.
Save maxdignan/a2ea539a18aaec2f3cfb to your computer and use it in GitHub Desktop.
Library to make Injectable functions with Dev-defined resource context
var DI = function(){
var throwDelayedError = function(typeOfErr, err){
setTimeout(function(){
throw typeOfErr + ': ' + err;
}, 0);
};
var injectables = {};
this.inject = function(name, value){
if (name && typeof name === 'object'){
Object.keys(name).forEach(function(key){
injectables[key] = name[key];
});
} else if (name && value){
injectables[name] = value;
}
return this;
};
this.run = function(dependencies, passedFunc){
var InjectableArray = [];
dependencies.forEach(function(singleDep){
if (injectables[singleDep]){
InjectableArray.push(injectables[singleDep]);
} else {
InjectableArray.push(undefined);
throwDelayedError('DependencyInjectionError', singleDep + ' is not available! - Called from dependency list ' + dependencies);
}
});
passedFunc.apply({}, InjectableArray);
};
};
//testing
var d = new DI();
d.inject('hello', function(num){
console.log('hi all ' + num);
});
d.inject('value', 7);
d.inject('m', 'im a string');
d.run(['hello', 'value'], function(hello, value){
console.log(hello);
console.log(value);
hello(value);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment