JavaScript: Understanding CustomEvent and dispatchEvent
In this article, I’ll try to explain how could we create and dispatch events using Event
, CustomEvent
constructors and dispatchEvent()
method. We’ll also explore how and for what purposes custom events and dispatchEvent are used in our projects.
I hope you will be able to create custom events by the end of this article.
So let’s get started! 🙌
A web application consists series of events and we can say that these events are one of the most essential parts of a web application.
In some cases, default JavaScript events don’t meet our requirements. For instance, in our applications, we are using some custom events which are not available in default JavaScript events to add notifications, refresh some data, etc. We’ll take a look at these in the rest of the article.
How can we create custom events?
There are two ways to create custom events.
- The first way is using an Event constructor.
- The second way is using the CustomEvent constructor which we prefer.
To add more data to the event object, the CustomEvent interface exists and the detail property can be used to pass custom data.
Event Constructor
You can create custom events with the Event constructor as follows:
Please note that event names are case-insensitive. So NOTIFICATION_ADD
is same as Notification_Add
or notification_add
.
const event = new Event('NOTIFICATION_ADD');
CustomEvent Constructor
As we mentioned above, if we want to add more data to the event object we can use the CustomEvent constructor as follows:
const event = new CustomEvent('NOTIFICATION_ADD', {
detail: {
title: 'Error!',
message: 'There was a problem creating your account.'
}
});
Dispatching the custom events
Well, the event was created. What’s next? Of course, we want to use it in our project. The last step of firing an event is calling the dispatchEvent() method. It accepts an event parameter inside which is an Event object.
Let me show you an example.
const event = new CustomEvent('NOTIFICATION_ADD', {
detail: {
title: 'Error!',
message: 'There was a problem creating your account.'
}
});
// We are dispatching the our custom event here.
window.dispatchEvent(event);
After that, you can add the event listener like below.
// Let's say we have a handleAddNotification function inside our project like below
function handleAddNotification(e) {
// logic here.
}
window.addEventListener('NOTIFICATION_ADD', handleAddNotification);
Finally, our file will look like this:
<button onclick="handleButtonClick()">
Create my account
</button>
const event = new CustomEvent('NOTIFICATION_ADD', {
detail: {
title: 'Error!',
message: 'There was a problem creating your account.'
}
});
function handleButtonClick(){
window.dispatchEvent(event);
}
function handleAddNotification(e) {
alert(e.detail.title + ' ' + e.detail.message);
}
window.addEventListener('NOTIFICATION_ADD', handleAddNotification);
You can see the working example here:
For what purposes and where do we use it?
Before you read you may want to look up these articles about micro frontend.
In CicekSepeti, we have a micro frontend architecture here and have custom components like a button, a tooltip, a notification, a checkbox, etc., and several fragments. Sometimes communication is needed between these components and fragments. Just at this point, the custom events help us.
If to talk about examples, we have a notification component on remote and want to display it on one of the pages after some transactions.
In this case, the notification component has an event listener named ‘NOTIFICATION_ADD’ and the page has a registration form. When the user presses the register button we make an API request and then display a success or error toast message via the dispatchEvent method and custom event constructor.
Thanks to the event listeners on the notification component, we can trigger our custom events that were defined previously in other projects where and whenever we want.
Summary
Using JavaScript custom events can improve both the user and development experience of your app when used properly. From now on, we know that we can use custom events when JavaScript’s default events like keyboard events, mouse events, etc. don’t meet our requirements.