From 9268676797025eb27eef2ac0f9028ed625aa4b49 Mon Sep 17 00:00:00 2001 From: Ayo Date: Sat, 16 Dec 2023 09:03:01 +0100 Subject: [PATCH] fix: static props makes state shared across class instances - uses structuredClone on static props - closes #28 --- examples/demo/Toggle.js | 16 ++++++++++++++++ examples/demo/index.html | 4 ++++ src/WebComponent.js | 15 ++++++--------- 3 files changed, 26 insertions(+), 9 deletions(-) create mode 100644 examples/demo/Toggle.js diff --git a/examples/demo/Toggle.js b/examples/demo/Toggle.js new file mode 100644 index 0000000..cecadb9 --- /dev/null +++ b/examples/demo/Toggle.js @@ -0,0 +1,16 @@ +import { WebComponent, html } from "../../src/index.js"; + +class Toggle extends WebComponent { + static props = { + toggle: false, + }; + get template() { + return html` + + `; + } +} + +customElements.define("my-toggle", Toggle); diff --git a/examples/demo/index.html b/examples/demo/index.html index 4d01297..9a4fb9c 100644 --- a/examples/demo/index.html +++ b/examples/demo/index.html @@ -8,8 +8,12 @@ + + + +

diff --git a/src/WebComponent.js b/src/WebComponent.js index d78e18b..5692174 100644 --- a/src/WebComponent.js +++ b/src/WebComponent.js @@ -168,15 +168,12 @@ export class WebComponent extends HTMLElement { } #initializeProps() { - let initialProps = {}; - if (this.constructor.props) { - initialProps = this.constructor.props; - Object.keys(initialProps).forEach((camelCase) => { - const value = initialProps[camelCase]; - this.#typeMap[camelCase] = typeof value; - this.setAttribute(getKebabCase(camelCase), serialize(value)); - }); - } + let initialProps = structuredClone(this.constructor.props) ?? {}; + Object.keys(initialProps).forEach((camelCase) => { + const value = initialProps[camelCase]; + this.#typeMap[camelCase] = typeof value; + this.setAttribute(getKebabCase(camelCase), serialize(value)); + }); if (!this.#props) { this.#props = new Proxy( initialProps,