Events play a crucial role in most of the code we write, whether it’s responding to user actions like mouse clicks or keyboard events, or handling network events like HTTP calls. While JavaScript provides built-in events to capture these actions, we can also create our own custom events in both browser and Node.js environments.

Custom Events in the Browser

In the browser, we can use the Event object to create a custom event. Here’s an example:

const anEvent = new Event('start');

To trigger the custom event, we can use the dispatchEvent() method on the document object:

document.dispatchEvent(anEvent)

When the custom event is triggered, we can listen for it using the addEventListener() method:

document.addEventListener('start', event => { 
 console.log('started!')
})

We can also pass custom data along with the event using the CustomEvent object instead of Event. The data can be passed as an object in the second parameter:

const anotherEvent = new CustomEvent('start', {
 detail: {
 color: 'white'
 }
})

In the event listener, we can access the custom data using the event.detail property:

document.addEventListener('start', event => { 
 console.log('started!')
 console.log(event.detail)
})

Custom Events in Node.js

In Node.js, we can achieve a similar custom event system using the events module. This module provides the EventEmitter class, which we can use to handle our events.

To initialize the EventEmitter, we need to require the events module and create an instance of the EventEmitter class:

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

The EventEmitter object exposes various methods, but two important ones for our purpose are emit() and on():

  • The emit() method is used to trigger an event.
  • The on() method is used to attach a callback function that will be executed when the event is triggered.

For example, let’s create a start event and log a message to the console when it is triggered:

eventEmitter.on('start', () => {
 console.log('started')
})

To trigger the event, we can use the emit() method:

eventEmitter.emit('start')

This will execute the callback function specified in the on() method and display the message in the console.

We can also pass arguments to the event handler by including them as additional arguments in the emit() method:

eventEmitter.on('start', (number) => {
 console.log(`started ${number}`)
})

eventEmitter.emit('start', 23)

Multiple arguments can be passed as well:

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

eventEmitter.emit('start', 1, 100)

In this way, we can create and handle custom events in both the browser and Node.js environments, allowing us to customize our event-driven code.