JavaScript Design Patterns — Behavioral — Observer
2 min readAug 12, 2024
The observer pattern allows for the definition of one-to-many dependency between objects so that all its dependents are notified and updated automatically when one object changes state.
In this example, we are creating a simple class product that other classes can observe registering about changes in the register() method. When something is updated, the notifyAll() method will communicate with all the observers about these changes.
class ObservedProduct {
constructor() {
this.price = 0;
this.actions = [];
}
setBasePrice(val) {
this.price = val;
this.notifyAll();
}
register(observer) {
this.actions.push(observer);
}
unregister(observer) {
this.actions.remove.filter(function (el) {
return el !== observer;
});
}
notifyAll() {
return this.actions.forEach(
function (el) {
el.update(this);
}.bind(this)
);
}
}
class Fees {
update(product) {
product.price = product.price * 1.2;
}
}
class Profit {
update(product) {
product.price = product.price * 2;
}
}
export { ObservedProduct, Fees, Profit };
A complete example is here 👉 https://stackblitz.com/edit/vitejs-vite-kyucyd?file=main.js
Conclusion