The Node.js Event emitter
On the backend side, Node.js offers us the option to build a similar system using the
This module, in particular, offers the
EventEmitter class, which we'll use to handle our events.
You initialize that using
This object exposes, among many others, the
emitis used to trigger an event
onis used to add a callback function that's going to be executed when the event is triggered
For example, let's create a
start event, and as a matter of providing a sample, we react to that by just logging to the console:
When we run
the event handler function is triggered, and we get the console log.
You can pass arguments to the event handler by passing them as additional arguments to
The EventEmitter object also exposes several other methods to interact with events, like
once(): add a one-time listener
off(): remove an event listener from an event
removeAllListeners(): remove all listeners for an event
You can read more about these methods in the official documentation.