I'm writing a Javascript custom element and want a event to bubbel past it's shadowDOM boundary. Catching the event inside the shadowDOM is no problem but how can I listen for the event in the lightDOM?
<div class="tasks">
<m-task name="Abc" number=123></m-task>
</div>
customElements.define('m-task',
class mTask extends HTMLElement {
constructor() {
super()
this.attachShadow({ mode: 'open' })
// ---> LISTENING FOR EVENT <---
this.addEventListener('connected', e => {
console.log(e.detail)
})
// ---> LISTENING FOR EVENT <---
this.addEventListener('disconnected', e => {
console.log(e.detail)
})
}
connectedCallback() {
console.log('connected', this)
this.dispatchEvent(new CustomEvent('connected', {
bubbles: true,
composed: true,
detail: {
type: 'connected',
value: 1234
}
}))
}
disconnectedCallback() {
console.log('disconnected', this)
this.dispatchEvent(new CustomEvent('disconnected', {
bubbles: true,
composed: true,
detail: {
type: 'disconnected',
value: -99
}
}))
}
})
// ---> LISTENING FOR EVENT <---
// THIS IS NOT WORKING
document.querySelector('.tasks').addEventListener('connected', e => {
console.log('listening in the light')
console.log(e.detail)
})
connected <m-task name="Abc" number="123">
Object { type: "connected", value: 1234 }
disconnected <m-task name="Abc" number="123">
Object { type: "disconnected", value: -99 }
waiting 1ms gives the expected result
setTimeout(() => {
this.dispatchEvent(new CustomEvent('connected', {
bubbles: true,
composed: true,
detail: {
type: 'connected',
value: 1234
}
}))
}, 1);