Web Wish 7: Custom Element Disconnected Signal
Managing lifecycles in custom elements can be tedious.
For instance, any event listener on global objects added in connectedCallback()
must be removed in disconnectedCallback()
.
This double bookkeeping is error-prone, and could be simpler.
Using an AbortController
can simplify things by automatically removing event listeners when the abort()
method is called.
class SomeElement extends HTMLElement {
#abortController
connectedCallback() {
this.#abortController?.abort()
this.#abortController = new AbortController()
document.addEventListener('scroll', () => {}, { signal: this.#abortController.signal })
}
disconnectedCallback() {
this.#abortController?.abort()
}
}
This process would be much cleaner if the HTMLElement offered a built-in disconnectedSignal()
.
Luckily, Keith Cirkel has proposed such a signal.
With this proposal, the example above would become:
class SomeElement extends HTMLElement {
connectedCallback() {
document.addEventListener('scroll', () => {}, { signal: this.disconnectedSignal() })
}
}
This Christmas, I'm wishing for a disconnectedSignal()
method to automatically remove event listeners
when an element is disconnected.
Relevant issues and PRs: