From 5b43358219402bee3eadf4a0f184a4b924d3293b Mon Sep 17 00:00:00 2001 From: Sam Atkins Date: Fri, 10 May 2024 14:48:26 +0100 Subject: [PATCH] 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. --- src/util/Component.js | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/util/Component.js b/src/util/Component.js index 4439e3ce2..40839c86a 100644 --- a/src/util/Component.js +++ b/src/util/Component.js @@ -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 () { - this.on_ready && this.on_ready(this.get_api_()); + if (!this.#has_called_on_ready) { + this.on_ready && this.on_ready(this.get_api_()); + this.#has_called_on_ready = true; + } } attach (destination) { - const el = this.create_element_(); - this.dom_.appendChild(el); + 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);