Custom Events: Creating and Dispatching
You'll learn: How to create and dispatch your own custom events to enable powerful component-to-component communication in your applications.
While the browser provides built-in events like click and keydown, you can create custom events to signal anything meaningful in your application—like "user-logged-in" or "cart-updated". This lets different parts of your page communicate without being tightly coupled together.
The Core Idea
Think of custom events like creating your own news channel. Instead of waiting for the browser to announce "click" or "submit", you become the broadcaster, announcing events that matter to your application. Other parts of your code can listen for these announcements and react accordingly.
Creating a Custom Event
Use the CustomEvent constructor to create an event with a custom name:
const myEvent = new CustomEvent('user-logged-in', {
detail: { username: 'alice', timestamp: Date.now() }
});
The detail property carries any data you want to pass along with the event—like shipping a package with your announcement.
Dispatching the Event
To broadcast your event, call dispatchEvent() on any DOM element:
const button = document.querySelector('#login-btn');
button.dispatchEvent(myEvent);
Listening for Custom Events
Use addEventListener() just like with built-in events:
button.addEventListener('user-logged-in', function(event) {
console.log('User logged in:', event.detail.username);
});
Why This Matters
Custom events let components communicate without knowing about each other directly. A login form can dispatch "user-logged-in", and a header, sidebar, and notification system can all independently listen and react—no tangled dependencies.
Key Takeaway: Custom events let you create your own event types using CustomEvent and dispatchEvent(), enabling flexible, decoupled communication between different parts of your application.