Custom Events & Event Dispatching
Custom Events & Event Dispatching in Modern JavaScript
While standard DOM events (click, input, keydown) handle direct user input, modular architectures require components to communicate domain-specific events—such as cart:item-added, modal:closed, or user:authenticated. The CustomEvent API allows you to create, dispatch, and intercept custom events across the DOM and Web Components.
1. Creating and Dispatching a CustomEvent
A CustomEvent takes an event type string and an optional initialization dictionary:
2. Listening to Custom Events & Accessing detail
Event payloads passed in { detail } are available on event.detail:
3. Crossing the Shadow DOM: composed: true
By default, events dispatched inside a Shadow DOM are trapped inside and cannot bubble up into the main document. Setting composed: true allows the event to penetrate through the shadow boundary into the outer Light DOM:
4. Making Custom Events Cancelable
If you set cancelable: true, listeners can call event.preventDefault(). The caller of dispatchEvent() receives a boolean indicating whether the action was permitted:
Practice Quiz
Debouncing vs Throttling Deep Dive
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Storage Quotas & Persistence Policies | Debouncing vs Throttling Deep Dive |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.