Add custom events in Javascript

Custom events in Javascript browser

Events are the integral part of programming irrespective of which programming language you are using.

For example I/O events like mouse click or keyboard events, network events when interact with HTTP calls.

These are in-built events which are provided by Javascript engine / browsers.

But many times you want to create your custom events and use them as per requirement.

In browsers you can use the Event object.

const customEvent = new Event('checkStatus');

This can be triggered like this.

document.dispatchEvent(customEvent);

And once it is triggered you can use the default event listener to listen the event.

document.addEventListener('checkStatus', event => {   
  console.log('Online!')
});

This is the most common way to create custom events if you don’t want to pass data along. If you want to pass some data then you will need to use CustomEvent, which accepts an object as second parameter in which we can pass any data.

const anotherEvent = new CustomEvent('checkStatus', {
  status: {
    isOnline: false
  }
});

And then while listening to the event using addEventListener we can fetch this data using the event object.

document.addEventListener('checkStatus', event => {   
  console.log('Online!');
  console.log(event.status);
});

Custom event in Nodejs

In nodejs, we can do the same thing using events module.

This module provides eventEmitter class, which can be used to create new events and then emit and listen to it.

const EventEmitter = require('events')
const eventEmitter = new EventEmitter()

This eventEmitter class contains on and emit methods.

  • emit is used to trigger an event.
  • on is called when the event is triggered, it expects a function as second argument which will be callback.

The good thing is we don’t necessarily have to register the event before emitting them.

eventEmitter.emit('customEvent');

And then listen it.

eventEmitter.on('customEvent', () => {
  console.log('online!');
});

We can also pass data, as arguments.

eventEmitter.emit('customEvent', 1, 100);

eventEmitter.on('customEvent', (start, end) => {
  console.log(`Online from ${start} to ${end}`)
})