Takeshi Tokugawa YD
Takeshi Tokugawa YD

Reputation: 923

Instance exchange between two ES6 classes

How I should to organize the interaction between two ES6 classes, it they uses instances of each other?

enter image description here

The below solution is working, however it's a little bit complicated.

let widgetA;
let widgetB = new WidgetB();

widgetA = new WidgetA(widgetB);
widgetB.initialize(widgetA);

class WidgetA {

    constructor(widgetB){
        this.widgetB = widgetB;
    }

    widgetAmethod(){
        this.widgetB.doSomethingWidthWidgetB();   
    }

}

class WidgetB {

    constructor(){
        this.widgetA;
    }

    initialize(widgetA){
        this.widgetA = widgetA;
    }

    widgetBmethod(){
        this.widgetA.doSomethingWidthWidgetA();
    }
}

Upvotes: 0

Views: 112

Answers (1)

Andre Goncalves
Andre Goncalves

Reputation: 3850

I think passing the instances into each widget makes the code too tightly coupled, difficult to test and extend. In these situations I prefer using something like pub/sub or custom events:

let widgetA = new WidgetA();
let widgetB = new WidgetB();

class WidgetA {
    constructor () {
        document.addEventListener('widgetAsomething', this.doSomethingWidthWidgetA, false);
    }

    widgetAmethod () {
        const event = new CustomEvent('widgetBsomething');
        document.dispatchEvent(event); 
    }

    doSomethingWithWidgetA () {}
}

class WidgetB {
    constructor () {
        document.addEventListener('widgetBsomething', this.doSomethingWidthWidgetB, false);
    }

    widgetBmethod () {
        const event = new CustomEvent('widgetAsomething');
        document.dispatchEvent(event);
    }

    doSomethingWithWidgetB () {}
}

There a are a lot of benefits to this approach, a future widgetC can easily trigger the WidgetA and B methods as well.

More info about custom events here: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

Upvotes: 1

Related Questions