re: Using Events In Node.js The Right Way VIEW POST


I'll flesh it out a bit more by providing some related details.

There are a few differences between the EventTarget in the browser and the EventEmitter from Node.

The EventEmitter class implements on, off and emit to register/unregister/fire events. In the EventTarget of window these are called addEventListener, removeEventListener and dispatchEvent.

The EventEmitter is chainable, the EventTarget in the browser is not.

// this works
emitter.on('user-registered', user => {
  console.log('new user registered!', user)
}).on('message', message => {
  console.log('received message!', message)

// this not works
document.body.addEventListener('DOMContentLoaded', console.log).addEventListener('error', console.error)

Although on is chainable, off is not. When you remove an event listener using off You can not add another .off to it. In my opinion this is inconsistent and bad practice but I don't want to debate it.

Using EventEmitter, you simply emit any type of object. In a window, EventTarget.dispatchEvent requires the second argument to be of type Event. This means that in order to emit a new event, in the browser you need to instantiate an Event for it.

document.body.dispatchEvent('ready', new Event('something is ready'))

If you want to deal with events in an even more sophisticated matter then have a look at eventemitter2 on NPM. It normalizes some inconsistencies and adds a few features such as wildcard type event listeners

// this will fire on user.ready, user.disconnect, user.whatever ...
myEvents.on('user.*', data => {
   console.log('something user related happened!', data)

But it can be done even better. If this stuff interests you then have a look at my Emitter class which is designed specifically to fill these gaps.


Thanks so much for the valuable input Jochem! If you don't mind, I might include eventemitter2 and wild card-based subscriptions in this article and on another platform where I published it.

code of conduct - report abuse