Creating Your Own Signals
Beyond built-in events (click, submit, keydown), you can create completely custom events. This allows different parts of your application to communicate with each other in a clean, decoupled way.
Why is this useful?
Think of a custom media player component. When the video ends, it can fire a custom video-end event. Any other part of the application can listen for this signal without the player needing to " know " about them directly.
Step 1: Create the Event
Pass your custom data inside the detail property:
let loginEvent = new CustomEvent('userLogin', {
detail: { username: 'JohnDoe', role: 'admin' },
bubbles: true // Let the event bubble up the DOM
});
Step 2: Fire (Dispatch) the Event
document.dispatchEvent(loginEvent);
Step 3: Listen for It
Exactly like listening for a regular click event:
document.addEventListener('userLogin', function(event) {
console.log('Welcome back, ' + event.detail.username + '!');
console.log('Your role is: ' + event.detail.role);
});
Note
Custom events do NOT bubble by default. If you want the event to travel up the DOM tree, you must explicitly set bubbles: true in the options object.