Bindings
There are three types of binding supported by the Container: Class Binding, Method Binding and Instance Binding.
Class Binding
$.bind(a contract).to(a class);
This maps a Contract to a Class. The component will be resolved by invoking the class's constructor at runtime. The example above already demonstrated this by binding 'a fuel tank' to the class FuelTank:
$.bind('a fuel tank').to(FuelTank);
Method Binding
$.bind(a contract).to(a method);
This maps a Contract with a Building Method that builds the component. The component will be resolved as returning result of method invocation. For example:
$.bind('my car').to(function(engine, fuelTank) {
var car = new Car(engine, fuelTank);
// more initialization here.
...
return car;
}).use('an engine', 'a fuel tank');
This approach is useful in case of building a component requires more complex steps than just calling its constructor.
Instance Binding
$.bind(a contract).to(an instance);
This maps a Contract with an instance and then returns that instance as the result of component resolution. This approach simply stores the component in the container so there is no needs to invoke any constructor/method.
For example, say you want to add Manufacturer information to your Car and display it:
function Manufacturer(name) {
this.name = name;
};
function Car(engine, fuelTank, manufacturer) {
this.toString = function() {
return `Manufacturer: ${manufacturer.name}`;
}
};
Create some manufacturers and store them in the container:
var BMW = new Manufacturer('BMW');
var Porsche = new Manufacturer('Porsche');
$.bind('BMW').to(BMW);
$.bind('Porsche').to(Porsche);
Now choose a favorite manufacturer for your car. For e.g Porsche:
$.bind('my car').to(Car).use('an engine', 'a fuel tank', 'Porsche'); // manufacturer comes last in Car's constructor.
// display car information in console:
console.log($('my car').toString()); // will be: "Manufacturer: Porsche"
Unlike Class Binding and Method Binding, Instance Binding requires a manual component instantiation by yourself. In consequence, it costs computer resources at registration. Too many Instance Binding statements at once may drastically draw your application performance. So you are recommended to avoid using this eager binding when possible and use lazy binding (Class Binding & Method Binding) instead.
Last updated