What Are Custom Events?
A custom event is a user-defined DOM event you create and dispatch in your application. Once you dispatch a custom event, you can listen for it just like any other DOM event using addEventListener
. This makes it easy for any part of your app to react—regardless of who fired it or where. Use them when built-in events (like click
, submit
, etc.) are too limiting or when you want to broadcast state changes across components or even separate apps loaded onto the same website.
Custom Event Constructor
This makes a minimal basic standard custom event that bubbles and can be canceled:
Dispatch Custom Event
When btn.dispatchEvent(evt)
is called, it fires the my-event
directly from the button. Since the event was created with bubbles: true
, it will naturally bubble up through the DOM.
Custom Event Listener
This listener reacts whenever my-event
is dispatched anywhere in the DOM, capturing the event’s target
to know which element originated it.
Example: Passing Data Through Custom Event
This pattern is ideal for broadcasting state changes or passing payloads across application modules. Here’s how to create and dispatch a CustomEvent
that carries data via the detail
property:
When to use Custom Events
- To decouple components in a modular way
- For communicating non-DOM triggers like fetch/WebSocket events
- To bridge different frameworks or components from diferent code bases loaded on same website (e.g., React → Angular)
Implementation Best Practices
- Namespacing: Prefix events clearly (e.g.,
app:user-saved
) to avoid name clashes - Name conventions: Use lowercase with hyphens (e.g.,
user-logged-in
) instead of camelCase - Leverage event options: Always think about
bubbles
,cancelable
, anddetail
in your constructor - Clean up listeners: Use
{ once: true }
or manually remove withremoveEventListener
to avoid memory leaks - Test & debug: Examine
e.detail
, event flow, and propagation using DevTools
No comments:
Post a Comment