Simply Container for using Dependency Injection pattern in JavaScript
Container.js is lightweight library (<2kb when minified), designed to facilitate how you can implement Dependency Injection pattern in your JavaScript applications. It works both versions of ECMAScript - 2015 (ES6) and 5 (ES5).
In order to use this package, you need to install it in your project:
via Bower (by default will be used ES5 version)
bower install Container.js --save
via NPM (by default will be used ES2015 version)
npm install node-container.js --save
or download it manually:
<script src="/path/to/Container.min.js"></script>
<script src="/path/to/Es2015-Container.js"></script>
- Removed callback from
Container.get
method - Gulp instead of Grunt
- Support for ES2015
void
Container
- Constructor - arguments: [Object<string, function> elements
]
Argument
elements
is optional. It allows to create default bindings for existing classes.
Example:
var appContainer = new Container({
"Date": Date
});
boolean
Container.prototype.has
- arguments: [string name
]
Return true if Container contains element with given name.
Example:
console.log(appContainer.has('Date')); // true
console.log(appContainer.has('MyObject')); // false
void
Container.prototype.bind
- arguments: [string name, function instance, string[]|function[] parameters
]
Binds given instance with given name. Each value in
parameters
array should be name of element in Container or function which return value of parameter.
Example:
appContainer.bind('Window', Window, ['Date']);
appContainer.bind('Door', Door, [function () { return Math.random(); }]);
void
Container.prototype.singleton
- arguments: [string name, function instance, string[]|function[] parameters
]
Binds given object as singleton in container. Parameters are the same like
Container.bind
method.
Example:
appContainer.singleton('Date', new Date());
appContainer.get('Date').setFullYear(2014);
appContainer.get('Date').getFullYear(); // 2014
mixed
Container.prototype.get
- arguments: [string name
]
Returns instance of earlier bound instance.
Example:
appContainer.get('Window'); // an Window instance
void
Container.prototype.remove
- arguments: [string name
]
Removes link between Container and given name.
Example:
appContainer.remove('Date');
appContainer.has('Date'); // false
Firstly need to install dev dependencies:
npm install
For running unit tests:
npm run gulp test
For build new dists version:
npm run gulp