The Observer Pattern: The EventEmitter Class
Learn about what the EventEmitter class is and how to create and use it.
We'll cover the following
Another important and fundamental pattern used in Node.js is the Observer pattern. Together with the Reactor pattern and callbacks, the Observer pattern is an absolute requirement for mastering the asynchronous world of Node.js.
The Observer pattern is the ideal solution for modeling the reactive nature of Node.js and a perfect complement for callbacks.
The Observer pattern defines an object (called subject) that can notify a set of observers (or listeners) when a change in its state occurs.
The main difference from the Callback pattern is that the subject can actually notify multiple observers, while a traditional CPS callback will usually propagate its result to only one listener, the callback.
The EventEmitter
class
In traditional object-oriented programming, the Observer pattern requires interfaces, concrete classes, and a hierarchy. In Node.js, all this becomes much simpler. The Observer pattern is already built into the core and is available through the EventEmitter
class. The EventEmitter
class allows us to register one or more functions as listeners, which are invoked when a particular event type is fired. The illustration given below visually explains this concept:
Get hands-on with 1400+ tech skills courses.