fix: Only run Component initialization functions once

If the Component gets removed from the DOM and then re-added, it already
has contents, and we don't need to create them again. It also has
already had on_ready called, so that doesn't need to happen again
either.

This fix stops Components duplicating their content elements and
listener callbacks whenever they're moved around the document.
This commit is contained in:
Sam Atkins 2024-05-10 14:48:26 +01:00
parent cf605c8a38
commit 5b43358219

View File

@ -1,6 +1,9 @@
import ValueHolder from "./ValueHolder.js";
export class Component extends HTMLElement {
#has_created_element = false;
#has_called_on_ready = false;
// Render modes
static NO_SHADOW = Symbol('no-shadow');
@ -86,12 +89,18 @@ export class Component extends HTMLElement {
}
connectedCallback () {
if (!this.#has_called_on_ready) {
this.on_ready && this.on_ready(this.get_api_());
this.#has_called_on_ready = true;
}
}
attach (destination) {
if (!this.#has_created_element) {
const el = this.create_element_();
this.dom_.appendChild(el);
this.#has_created_element = true;
}
if ( destination instanceof HTMLElement ) {
destination.appendChild(this);