/*Subject is the observed and notifies all observers of any changes in its state */
class Subject {
constructor(){
this.state = "Initial state";
this.observers = [];// Store all observers, and notify all observers when their state changes
this.addobserver = function (observertmp) {
this.observers.push(observertmp);
}
this.changeState = function (data) {
console.log("State changed, notify all subscribers (observers)");
for(let i=0; i<this.observers.length; i++){this.observers[i].update(data);
}
this.state = data; }}}// An Observer is an Observer, and when changed by the Observer, the Observer calls its Update method
class Observer{
constructor(){
this.update = function(data){
console.log("Observer: Found state changed, new state value is"+data); }}}let observerOne = new Observer();
let observerTwo = new Observer();
let subject = new Subject();
subject.addobserver(observerOne);
subject.addobserver(observerTwo);
/* The observed state changes */
subject.changeState("new state");
Copy the code
Once the observed state changes, all observers will receive the new state: