liveBook · Manning

Composed property

As explained in Web Components in Action

The composed property is a DOM event option that determines whether an event can propagate across a shadow boundary.

The composed property controls whether a DOM event can cross a Shadow DOM boundary. Set composed to true when a custom event should propagate from inside a component to the containing document; bubbling remains a separate option. section 14.3

Passing a custom event outward

A button listener creates CustomEvent('myclick', { bubbles: true, composed: true, detail: { message: 'hi', number: 5 } }). Dispatching it from the shadow tree lets the event path continue through the component, document, and Window.

Listing 14.7. Passing a Custom Event through the Shadow DOM
<html>
<head>
   <title>Shadow DOM Custom Events</title>
   <script>
       class SampleComponent extends HTMLElement {
           connectedCallback() {
               const shadow = this.attachShadow({mode: 'open'});
               shadow.innerHTML = '<button>Click me</button>';
               shadow.querySelector('button').addEventListener(
                      'click', e => {                                       #1
                              const customEvent = new CustomEvent('myclick', {
                              bubbles: true,
                              composed: true,
                              detail: {
                                     message: 'hi',
                                     number: 5
                              }
                   });
                   shadow.dispatchEvent(customEvent);
               })
           }
       }
       customElements.define('sample-component', SampleComponent);

       document.addEventListener(                                           #2
               'myclick', function(e) {
           console.log('was clicked', e.target, e.currentTarget,
                        e.composedPath());
       });
   </script>
</head>

<body>
<sample-component></sample-component>
</body>
</html>

Inspect the complete Web Component example, including the custom event options and dispatch logic. section 14.3

How Web Components in Action covers it

How deep it goes
Explains boundary crossing through event paths and demonstrates composed alongside bubbles, without detailing browser internals.
Examples
Uses a button inside an open Shadow DOM to dispatch a custom event toward the containing document.
What it assumes
Assumes familiarity with DOM events, Web Components, Shadow DOM, and event bubbling.
What you can do after
Apply it via CustomEvent options to expose component events beyond a Shadow DOM boundary.
How it connects
Connects Shadow DOM, CustomEvent, event bubbling, event.target, and composedPath().

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.