Custom Events in JavaScript: Reacting to Events in a Customized Way
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:
1 | const anEvent = new Event('start'); |
To trigger the custom event, we can use the dispatchEvent()
method on the document
object:
1 | document.dispatchEvent(anEvent) |
When the custom event is triggered, we can listen for it using the addEventListener()
method:
1 | document.addEventListener('start', event => { |
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:
1 | const anotherEvent = new CustomEvent('start', { |
In the event listener, we can access the custom data using the event.detail
property:
1 | document.addEventListener('start', event => { |
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:
1 | const EventEmitter = require('events') |
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:
1 | eventEmitter.on('start', () => { |
To trigger the event, we can use the emit()
method:
1 | 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:
1 | eventEmitter.on('start', (number) => { |
Multiple arguments can be passed as well:
1 | eventEmitter.on('start', (start, end) => { |
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.