Custom Events
Beyond the built-in DOM events, you can create and dispatch your own custom events. This enables loosely coupled component communication — one part of your application can emit a named event, and any other part can listen for it, without them being directly coupled.
Creating Custom Events
Use the CustomEvent constructor with an event name and an options object. The detail property of the options carries arbitrary payload data. Set bubbles: true to allow the event to bubble up the DOM.
Dispatching Events
Call element.dispatchEvent(event) to fire the event on a DOM element. Any listener registered for that event name on the element or its ancestors (if bubbling) will be triggered.
Listening for Custom Events
Custom events are listened for exactly like built-in events, using addEventListener with the event name as a string. Access the payload via event.detail inside the handler.