intermediate
Custom events
Use CustomEvent for decoupled browser communication while controlling detail payloads, bubbling, and boundaries.
CustomEvent lets browser code publish semantic events without coupling callers to implementation details. The event can carry a detail payload and can opt into bubbling or crossing shadow boundaries. It is useful for web components and isolated widgets, but application state still needs clear ownership.
panel.dispatchEvent(
new CustomEvent('panel:save', {
bubbles: true,
composed: true,
detail: { id: panel.dataset.id },
})
);
Consumers should treat detail as read-only notification data. Mutable shared objects in detail couple siblings silently.
On interviews: interviewers look for when custom events are cleaner than direct callbacks and when they become hidden global control flow.
Common pitfalls: large mutable detail payloads couple consumers. Events are notifications, not a replacement for explicit state modeling.
The trade-off is convenience versus control — pick the mechanism that matches your coupling and performance budget.
Checklist:
- Name events semantically and document them.
- Keep detail small and immutable where possible.
- Decide bubbling and composed deliberately.
- Do not use events as the only source of truth.