Skip to content

Instantly share code, notes, and snippets.

@SSilence
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SSilence/3c84b5ef5fd3162ab1fe to your computer and use it in GitHub Desktop.
Save SSilence/3c84b5ef5fd3162ab1fe to your computer and use it in GitHub Desktop.
dependency injection
/**
* simple dependency injection
*
* @copyright Copyright (c) Tobias Zeising (http://www.aditu.de)
* @license GPLv3 (http://www.gnu.org/licenses/gpl-3.0.html)
*/
var injectCallable = {};
var injectObjects = {};
var define = function(name, obj) {
injectCallable[name] = obj;
};
var injectPlaceholder = function(name) {
this.name = name;
this.injectPlaceholder = true;
};
var injected = function(name) {
return new injectPlaceholder(name);
};
var inject = function(name) {
if (typeof injectCallable[name] == 'undefined')
throw name + " was not found";
if (typeof injectObjects[name] == 'undefined') {
injectObjects[name] = new injectCallable[name]();
for (property in injectObjects[name]) {
if (typeof injectObjects[name][property].injectPlaceholder != 'undefined')
injectObjects[name][property] = inject(injectObjects[name][property].name);
}
}
return injectObjects[name];
};
@SSilence
Copy link
Author

Simple dependency injection. Example:

define('oneclass', function() {
    this.foo = 'bar';
});

define('anotherclass', function() {
    this.oneclass = injected('oneclass');
});

var anotherclass = inject('anotherclass');
console.info(anotherclass.oneclass.foo); // 'bar'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment