Member-only story
Observer Design Pattern in JavaScript
Everything you need to know about the Observer design pattern in JavaScript
While working with any language, we tend to use several reusable design solutions to commonly occurring problems. In JavaScript, too, we have a mix of well-defined patterns.
The Observer pattern is one of them.
In this article, we shall understand more about the Observer design pattern in JavaScript and implement a small example in vanilla JavaScript.
What Is the Observer Design Pattern?
The Observer pattern follows a subscription model, where a subscriber (commonly referred to as the observer) subscribes to an event or an action handled by a publisher (commonly referred to as the subject) and is notified when the event or action occurs.
The subject broadcasts the occurrence of the event or action to all the observers.
When the observer no longer wishes to be notified of the changes by the subject, it unsubscribes itself from the subject, and the subject then removes it from the list of subscribers.
An Observer design pattern is very similar to a Publisher/Subscriber pattern, with a small difference that a Publisher/Subscriber pattern also specifies a…