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
