The observer pattern in TypeScript

PHOTO EMBED

Wed Jun 01 2022 20:50:36 GMT+0000 (Coordinated Universal Time)

Saved by @soyreynald #typescript #javascript

interface Observer{
   update:() => void;
}

class ConcreteObserverA implements Observer {
   update() {
        console.log(this.constructor.name,"has been updated");
   }
}

class ConcreteObserverB implements Observer {
   update () {
        console.log(this.constructor.name,"has been updated");
   }
}
class Subject {
    private _name = "";

    private observerCollection:Observer[] = [];

    get name() {
        return this._name;
    }

    set name(val:string) {
        this._name=val;
        this.notifyObservers();
    }

    registerObserver(...o:Observer[]) {
            this.observerCollection.push(...o);
    }

    unregisterObserver(o:Observer) { 
        this.observerCollection = this.observerCollection.filter (e => e! == o);
    }

    notifyObservers() {
        this.observerCollection.forEach(o => o.update() );
    }
}

const subject = new Subject();
const oA = new ConcreteObserverA();
const oB = new ConcreteObserverB();
subject.registerObserver(oA, oB);

subject.name = "Jau, jau!";
content_copyCOPY

This pattern is special to model one to many relationships. It "observes" the change in one element and triggers a change in the other objects.

https://www.youtube.com/watch?v=45TeJEmcqk8&list=PLREW9ZuU80uTfmxo61-acnUYk3P_4plIF&index=7