Getting Started
Import the container to your code:
const { container } = require('robo-toolkit');
or use $
to simplify its name, should you haven't used this symbol yet:
const $ = require('robo-toolkit').container;
The container
itself is a global singleton Container. In some cases you may want to use a different container (e.g module-level container) for your own purposes. To do so:
const myContainer = container.create();
Let's say you want to build a car that has an engine and a fuel tank. When the car starts, it checks if the fuel tank is empty or not. If not, it starts the engine, otherwise it asks you to refuel.
function FuelTank () {
this.isEmpty = function() {
return false;
}
}
function Engine() {
this.start = function() {
console.log('Engine started');
}
}
function Car(engine, fuelTank) {
this.start = function() {
console.log('Car starting...');
if (fuelTank.isEmpty()) {
console.log('Out of fuel. Please refuel.');
return;
}
engine.start();
console.log('Car started. Ready to go.');
}
}
You can use Class declaration instead of Function, as they are one and Robo-Container naturally supports ES6 Class declaration
Use container to map the Engine to any name you want. For example:
$.bind('an engine').to(Engine);
From now whenever 'an engine' is used in a dependency, it should be satisfied with an instance of Engine. Do the same for FuelTank:
$.bind('a fuel tank').to(FuelTank);
For the Car, more than a name, it needs 'an engine' and 'a fuel tank':
$.bind('my car').to(Car).use('an engine', 'a fuel tank');
Notice the order of Engine and FuelTank in the statement above. The 'an engine' must be placed first as Engine comes first in Car's constructor respectively.
Now build your Car and start it:
$.resolve('my car').start();
Or:
$('my car').start();
Run the application. Output displayed in console will look like:
Car starting...
Engine started
Car started. Ready to go.
Last updated