The observer pattern in JavaScript
The observer pattern allows an object (the observable or subject) to maintain a list of other objects that depend on it (observers). When a state update occurs in the subject, such as an entity object being created or updated, it notifies the observers.
Implementation
A sample use case for the observer pattern is an in-memory queue. The Queue
instance will have the subscribe
, unsubscribe
, and notify
methods.
subscribe
will add an additional “handler” function, unsubscribe
will remove a particular “handler” function if it has been registered, and finally, notify
will call each handler with a “message” payload. This is the “notification of the observers” piece, where the observable or subject ensures that each registered observer is notified.
subscribe
and unsubscribe
turn “observer” functionality on and off, respectively. subscribe
has to be used to become an “...