From e4a5ce37bd828fc990d00528538846634e35cfd7 Mon Sep 17 00:00:00 2001 From: Ayo Date: Sun, 17 Sep 2023 14:45:46 +0200 Subject: [PATCH] feat: static `properties` --- README.md | 11 ++++------- WebComponent.mjs | 12 ++++++++++++ demo/HelloWorld.mjs | 4 +--- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index ae8cb27..fca8357 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Web Component Base --- This is a very minimal base class for creating reactive custom elements easily. -When you extend the `WebComponent` class for your component, you only have to define the `template()` and `observedAttributes()`, and changes in any attribute value will automatically cause the UI to render. +When you extend the `WebComponent` class for your component, you only have to define the `template()` and `properties`, and changes in any attribute value will automatically cause the UI to render. The result is a reactive UI on attribute changes. @@ -44,9 +44,7 @@ class HelloWorld extends WebComponent { name = "World"; emotion = "excited"; - static get observedAttributes() { - return ["name", "emotion"]; - } + static properties = ["name", "emotion"]; get template() { return ` @@ -97,9 +95,8 @@ If you want a quick start example to copy, this is an example of using a custom import WebComponent from "https://unpkg.com/web-component-base"; class HelloWorld extends WebComponent { - static get observedAttributes() { - return ['name']; - } + static properties = ["name", "emotion"]; + get template() { return `

Hello ${this.name || 'World'}!

`; } diff --git a/WebComponent.mjs b/WebComponent.mjs index e0edc0f..770cdf5 100644 --- a/WebComponent.mjs +++ b/WebComponent.mjs @@ -1,10 +1,22 @@ // @ts-check export class WebComponent extends HTMLElement { + /** + * @type Array + */ + static properties = []; + + /** + * @returns string + */ get template() { return ""; } + static get observedAttributes() { + return this.properties; + } + /** * triggered when the component is connected to the DOM */ diff --git a/demo/HelloWorld.mjs b/demo/HelloWorld.mjs index f414694..5e055eb 100644 --- a/demo/HelloWorld.mjs +++ b/demo/HelloWorld.mjs @@ -5,9 +5,7 @@ export class HelloWorld extends WebComponent { name = "World"; emotion = "excited"; - static get observedAttributes() { - return ["name", "emotion"]; - } + static properties = ["name", "emotion"]; onChanges({ property, previousValue, currentValue }) { console.log(">>> changed", { property, previousValue, currentValue });