Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 39 ยท Events and Properties

Custom Events and Component Communication

Let components talk to the page with CustomEvent. Learn naming, detail payloads, bubbles and composed, cancelable events, and the properties-down, events-up pattern.

A reusable component should not reach into the page and change things. It should announce what happened and let the outside decide what to do. The browser's tool for this is the event system, and for your own announcements you use CustomEvent.

The guiding pattern is properties down, events up: a parent passes data into a child with attributes and properties, and the child reports user actions upward with events. It keeps components independent, testable and easy to reuse in any framework.

flowchart TB
  P["Page or parent"] -- "attributes / properties" --> C["Component"]
  C -- "CustomEvent" --> P

Data flows down through the API; notifications flow up through events.

Dispatching a CustomEvent

new CustomEvent(type, options) creates an event; dispatchEvent() sends it from an element. The detail option carries any data you want listeners to receive.

A counter that announces changes

The page listens with the normal addEventListener, exactly as it would for click. Nothing about the component is special to the listener.

Naming events

  • Use lowercase, hyphenated names such as item-select or count-change. Native events are lowercase single words (click, input, change), and a hyphen avoids future clashes.
  • Name events after what happened, in past or neutral terms: selected, value-change, toggle. Avoid names that command, such as do-save.
  • Do not reuse a native name for something different. If you wrap an input and re-dispatch change, it should mean what change means.

The options that matter

Option Default Meaning
detail null Data attached to the event, read as event.detail
bubbles false Whether the event travels up through ancestors
composed false Whether it can cross a shadow DOM boundary
cancelable false Whether a listener may call preventDefault()

bubbles is what makes event delegation possible: one listener on a list can catch events from every item. composed matters when your component uses a shadow root, which you will see in the next lesson on event retargeting and composed events.

Cancelable events

dispatchEvent returns false if a listener called preventDefault() on a cancelable event. That gives the outside world a veto, just like the native submit event.

Letting the page cancel an action

Tick the checkbox and press the button: the component asks permission first and respects the answer. This "before and after" pair is a common design.

Event delegation with bubbling

Because the events bubble, a parent can listen once for many children:

JavaScript
list.addEventListener("item-select", (event) => {
  console.log("selected", event.detail.id);
});

Inside the handler, event.target tells you which element dispatched the event. If your component uses shadow DOM, the target may be retargeted to the host; use event.detail to carry the exact identity you need.

Typed detail and documentation

Treat the event as part of your public API. Document its name and the shape of detail. In TypeScript projects, you can describe it once and use it everywhere:

TypeScript
interface CountChangeDetail { count: number }
type CountChangeEvent = CustomEvent<CountChangeDetail>;

Keep detail small and serializable: plain objects with primitive values. Do not pass the component's internal elements; that leaks implementation details.

Listening from inside the component

A component can also listen to events on itself or on its own children, using this.addEventListener. Add listeners in connectedCallback and remove any on document or window in disconnectedCallback, otherwise a removed component keeps being called and cannot be garbage collected.

JavaScript
connectedCallback() {
  this.onKey = (e) => { if (e.key === "Escape") this.close(); };
  document.addEventListener("keydown", this.onKey);
}
disconnectedCallback() {
  document.removeEventListener("keydown", this.onKey);
}

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do you put the data you want listeners to receive?

    CustomEvent carries arbitrary data in its detail property.
  2. 2. What does bubbles: true allow?

    Bubbling sends the event up through the parent chain. Crossing a shadow root additionally needs composed: true.
  3. 3. How do you let the page veto an action?

    dispatchEvent returns false when a listener called preventDefault on a cancelable event.
  4. 4. Why remove document-level listeners in disconnectedCallback?

    A document listener keeps a reference to the component alive and runs after it has been removed.

Summary

  • Components announce things with CustomEvent; the page decides what to do.
  • Use hyphenated lowercase names and keep detail small and plain.
  • bubbles, composed and cancelable control reach and veto power.
  • Properties go down, events go up; clean up outside listeners on disconnect.

Next: Event Retargeting and Composed Events