function Observable() {
this.observers = [];
}
Observable.prototype = {
subscribe(fn) {
this.observers.push(fn);
},
unsubscribe(fn) {
this.observers = this.observers.filter((observer) => observer !== fn);
},
notify() {
this.observers.forEach((observer) => {
if (typeof observer === "function") {
observer();
}
});
},
};
function changeName() {
console.log("change name is called");
}
function changeAge() {
console.log("change age is called");
}
const observe = new Observable();
observe.subscribe(changeAge);
observe.subscribe(changeName);
observe.notify();
// change age is called
// change name is called
Observer Pattern
Using ES5 syntax
class Observable {
constructor() {
this.observers = [];
}
subscribe(fn) {
this.observers.push(fn);
}
unsubscribe(fn) {
this.observers = this.observers.filter((observer) => observer !== fn);
}
notify() {
this.observers.forEach((observer) => {
if (typeof observer === "function") {
observer();
}
});
}
}
function changeName() {
console.log("change name is called");
}
function changeAge() {
console.log("change age is called");
}
const observe = new Observable();
observe.subscribe(changeAge);
observe.subscribe(changeName);
observe.notify();
// change age is called
// change name is called