Component Life Cycle

Transient

By default, Class Binding and Method Binding implicitly set component life cycle to Transient. Meaning everytime a$(contract)is called, it will return a different component in result.

In the below sample, two calls to$('my car')will return two different instances of Car:

$.bind('my car').to(Car).use('an engine', 'a fuel tank');

var car1 = $('my car');
var car2 = $('my car'); // a different car, different engine and fuel tank.

Singleton

Contrary to Transient, Singleton restricts number of instances of a particular type to only one. Meaning multiple calls to$(contract)will return the same component at all time.

Instance Binding is already singleton as component resolution returns the instance given in binding statement.

var i = 0;

function Sequence() {
    this.seq = ++i;

    this.toString = function() {
        return `SEQ: ${this.seq}`;
    }
};

$.bind('a sequence').to(new Sequence()); // Instance Binding.

console.log($('a sequence')); // "SEQ: 1"
console.log($('a sequence')); // "SEQ: 1"
console.log($('a sequence')); // "SEQ: 1"

As told, Instance Binding has some drawbacks compared to Class Binding and Method Binding. You may want to use Singleton with Class Binding and Method Binding for their advantages. To make a Class Binding or Method Binding singleton, place.asSingleton()after.to()or at the end of binding statement. Following statement specifies that class Sequence will has only one singleton instance:

$.bind('a sequence').to(Sequence).asSingleton();

Similarily, a Method Binding will be singleton if.asSingleton()is specified:

$.bind('a sequence').to(function () { return new Sequence() }).asSingleton();

Following statements will print the same result to console:

console.log($('a sequence')); // "SEQ: 1"
console.log($('a sequence')); // "SEQ: 1"
console.log($('a sequence')); // "SEQ: 1"

Let's get back to your Car. As there is only one manufacturer called BMW in the world, you can make 'BMW' singleton with Method Binding:

$.bind('BMW').to(function() { return new Manufacturer('BMW')}).asSingleton();

or with Class Binding:

$.bind('BMW').to(Manufacturer).use($.value('BMW')).asSingleton();

Now if you have a BMW and so does Peter, his car and yours will refer to the same manufacturer, BMW.

$.bind('my car').to(Car).set({ manufacturer: 'BMW' });
$.bind('Peter car').to(Car).set({ manufacturer: 'BMW' });

var myCar = $('my car');
var PeterCar = $('Peter car'); // different with myCar, but same manufacturer.

What about a singleton Engine? No. Considering every single car has its own engine so making Engine singleton is a no-no.

Last updated