feat: static properties

This commit is contained in:
Ayo 2023-09-17 14:45:46 +02:00
parent 596896b0f0
commit e4a5ce37bd
3 changed files with 17 additions and 10 deletions

View file

@ -4,7 +4,7 @@ Web Component Base
--- ---
This is a very minimal base class for creating reactive custom elements easily. 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. The result is a reactive UI on attribute changes.
@ -44,9 +44,7 @@ class HelloWorld extends WebComponent {
name = "World"; name = "World";
emotion = "excited"; emotion = "excited";
static get observedAttributes() { static properties = ["name", "emotion"];
return ["name", "emotion"];
}
get template() { get template() {
return ` 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"; import WebComponent from "https://unpkg.com/web-component-base";
class HelloWorld extends WebComponent { class HelloWorld extends WebComponent {
static get observedAttributes() { static properties = ["name", "emotion"];
return ['name'];
}
get template() { get template() {
return `<h1>Hello ${this.name || 'World'}!</h1>`; return `<h1>Hello ${this.name || 'World'}!</h1>`;
} }

View file

@ -1,10 +1,22 @@
// @ts-check // @ts-check
export class WebComponent extends HTMLElement { export class WebComponent extends HTMLElement {
/**
* @type Array<string>
*/
static properties = [];
/**
* @returns string
*/
get template() { get template() {
return ""; return "";
} }
static get observedAttributes() {
return this.properties;
}
/** /**
* triggered when the component is connected to the DOM * triggered when the component is connected to the DOM
*/ */

View file

@ -5,9 +5,7 @@ export class HelloWorld extends WebComponent {
name = "World"; name = "World";
emotion = "excited"; emotion = "excited";
static get observedAttributes() { static properties = ["name", "emotion"];
return ["name", "emotion"];
}
onChanges({ property, previousValue, currentValue }) { onChanges({ property, previousValue, currentValue }) {
console.log(">>> changed", { property, previousValue, currentValue }); console.log(">>> changed", { property, previousValue, currentValue });