Add disconnected handling parallel to connected

This commit is contained in:
Talia 2021-08-03 14:42:40 +02:00
parent d620c8528a
commit 73a6c6767d

View file

@ -56,6 +56,23 @@ export class Better extends HTMLElement {
this.#connected = [] this.#connected = []
} }
// Array of disconnected callbacks
#disconnected = [];
// disconnectedCallback but as a promise.
// Resolves instantly when already disconnected and can be used more than once.
get disconnected() {
if (this.isDisconnected) return Promise.resolve(this)
else return new Promise( (yes, no) => this.#disconnected.push({yes, no}) )
}
// Resolves all `disconnected promises
disconnectedCallback() {
if ("onDisconnect" in this) this.onDisonnect()
this.#disconnected.forEach( e => e.yes(this) )
this.#disconnected = []
}
setContent(...content) { setContent(...content) {
this.innerHTML = "" this.innerHTML = ""
content.forEach( element => this.appendChild(element) ) content.forEach( element => this.appendChild(element) )