feat: expose onChanges hook

This commit is contained in:
Ayo 2023-09-17 00:48:01 +02:00
parent 4b72ebeb08
commit 4e122a827d
3 changed files with 54 additions and 22 deletions

View file

@ -60,3 +60,29 @@ In your HTML page:
The result is a reactive UI that updates on attribute changes: The result is a reactive UI that updates on attribute changes:
<img alt="UI showing feeling toward Web Components changing from SAD to EXCITED" src="https://git.sr.ht/~ayoayco/web-component-base/blob/main/assets/wc-base-demo.gif" width="400" /> <img alt="UI showing feeling toward Web Components changing from SAD to EXCITED" src="https://git.sr.ht/~ayoayco/web-component-base/blob/main/assets/wc-base-demo.gif" width="400" />
### Hooks
Currently, you can define behavior when an attribute value changes by defining a method `onChanges` in your component:
```js
import WebComponent from "../index.mjs";
export class HelloWorld extends WebComponent {
name = "World";
emotion = "excited";
static get observedAttributes() {
return ["name", "emotion"];
}
onChanges({ previousValue, currentValue }) {
console.log(">>> changed", { previousValue, currentValue });
}
get template() {
return `
<h1>Hello ${this.name}${this.emotion === "sad" ? ". 😭" : "! 🙌"}</h1>`;
}
}
```

View file

@ -1,23 +1,29 @@
// @ts-check // @ts-check
export class WebComponent extends HTMLElement { export class WebComponent extends HTMLElement {
get template() {
get template () { return "";
return ''
} }
/**
* triggered when an attribute value changed
*/
onChanges({ previousValue, currentValue }) {}
connectedCallback() { connectedCallback() {
this.render() this.render();
} }
attributeChangedCallback(property, prev, value) { attributeChangedCallback(property, previousValue, currentValue) {
if (prev !== value) { if (previousValue !== currentValue) {
this[property] = value this[property] = currentValue;
this.render() this.render();
} }
this.onChanges({previousValue, currentValue});
} }
render() { render() {
this.innerHTML = this.template this.innerHTML = this.template;
} }
} }

View file

@ -9,14 +9,14 @@ export class HelloWorld extends WebComponent {
return ["name", "emotion"]; return ["name", "emotion"];
} }
onChanges({ previousValue, currentValue }) {
console.log(">>> changed", { previousValue, currentValue });
}
get template() { get template() {
return ` return `
<h1>Hello ${this.name}${ <h1>Hello ${this.name}${this.emotion === "sad" ? ". 😭" : "! 🙌"}</h1>`;
this.emotion === 'sad'
? '. 😭'
: '! 🙌'
}</h1>`
} }
} }
customElements.define('hello-world', HelloWorld); customElements.define("hello-world", HelloWorld);