transfuse.js
Transfuse.js is a lightweight JavaScript dependency injection container. Although not required, the developer is encouraged to use this library in conjunction with a more robust AMD module loader (e.g. RequireJS).
Moderately complex JavaScript applications frequently contain shared objects that are referenced throughout the codebase. Transfuse.js provides the developer with a single container with which they can store and reference those objects throughout their application.
Additional Information
- Read a very concise summary of the concept of dependency injection here.
- Shared objects have their place, but at a certain point you should also be promoting “loose coupling” via PubSub (“publish / subscribe”) throughout your application with the help of additional libraries such as Postal.js.
Example Usage
Defining Dependencies
Dependencies are stored for later reference via the set() method.
define([
'Dependency1',
'Dependency2',
'transfuse'
], function(Dependency1, Dependency2, transfuse) {
var dependency1 = new Dependency1();
var dependency2 = new Dependency2();
transfuse.set(‘dependency1’, dependency1);
transfuse.set(‘dependency2’, dependency2);
/*
Multiple dependencies can be stored with a single call to set() like so:
transfuse.set({
‘dependency1’: dependency1,
‘dependency2’: dependency2
});
*/
});
Referencing Dependencies
Requesting Specific Dependencies By Name
Once your transfuse dependency container has been setup, you can reference individual dependencies by name via the get() method.
define([
‘transfuse’
], function(transfuse) {
var dependency1 = transfuse.get(‘dependency1’);
});
Extending an Object with Multiple Dependencies
Mix multiple dependencies with an object via the extend() method.
define([
‘transfuse’
], function() {
transfuse.extend(this, [‘dependency1’, ‘dependency2’]);
console.log(this.dependency1 instanceof Dependency1); // true
console.log(this.dependency2 instanceof Dependency2); // true
});
Creating ‘Contexts’
Transfuse’s set(), get(), and extend() methods all share a single “sandbox” within which dependencies are defined and referenced. If you need a greater degree of segmentation, you can create additional sandboxes as shown below.
define([
‘Dependency3’,
‘transfuse’
], function(Dependency3, transfuse) {
var dependency3 = new Dependency3();
var other = transfuse.createContext(‘other’);
other.set(‘dependency3’, dependency3);
});
Installation
Bower
$ bower install transfuse