How to use custom events in Javascript
With Javascript you can listen to browser events like clicks, resizing, storage changes, focus, blur and so on with the common listeners like:
button.addEventListener("click", myFunction);
But what if you want to trigger an event yourself? You can create it with the CustomEvent
class, dispatch it and listen as with normal events:
// Create the event
const customEvent = new CustomEvent("myCustomEvent", {
detail: { message: "Hello, World!" }
});
// Listen for the event
document.addEventListener("myCustomEvent", (event) => {
console.log("Custom event triggered:", event.detail.message);
});
// Dispatch the event
document.dispatchEvent(customEvent);
Here's some use cases:
-
Extending Third-Party Libraries: Enhance or extend the functionality of third-party libraries without modifying their core code. For example Adding a custom "dataLoaded" event to a third-party charting library to trigger actions after chart data has been fetched.
-
Decoupling Logic: when implementing loosely coupled components, custom events allow one part of the code to trigger behavior in another without direct references.
-
Creating a Pub/Sub System: custom events can be the foundation for a simple publish-subscribe (pub/sub) system for inter-module communication. For example an e-commerce site where adding an item to the cart publishes a "cartUpdated" event, and other modules (like cart display or analytics) subscribe to it.
-
Track user interactions or application state changes in a centralized analytics module: Emitting a "pageViewed" event when a user navigates to a new page.
-
Asynchronous Operations: Signal completion of asynchronous tasks to other parts of the application. For example a "dataReady" event when an API call returns data, enabling components to update their content.
There are other solutions for the use cases above that may be often cleaner, but sometimes custom events are convenient and a good tool to have.