feat: expose onChanges hook
This commit is contained in:
parent
4b72ebeb08
commit
4e122a827d
3 changed files with 54 additions and 22 deletions
26
README.md
26
README.md
|
@ -60,3 +60,29 @@ In your HTML page:
|
|||
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" />
|
||||
|
||||
### 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>`;
|
||||
}
|
||||
}
|
||||
```
|
|
@ -1,23 +1,29 @@
|
|||
// @ts-check
|
||||
|
||||
export class WebComponent extends HTMLElement {
|
||||
get template() {
|
||||
return "";
|
||||
}
|
||||
|
||||
get template () {
|
||||
return ''
|
||||
/**
|
||||
* triggered when an attribute value changed
|
||||
*/
|
||||
onChanges({ previousValue, currentValue }) {}
|
||||
|
||||
connectedCallback() {
|
||||
this.render();
|
||||
}
|
||||
|
||||
attributeChangedCallback(property, previousValue, currentValue) {
|
||||
if (previousValue !== currentValue) {
|
||||
this[property] = currentValue;
|
||||
this.render();
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
this.render()
|
||||
}
|
||||
this.onChanges({previousValue, currentValue});
|
||||
}
|
||||
|
||||
attributeChangedCallback(property, prev, value) {
|
||||
if (prev !== value) {
|
||||
this[property] = value
|
||||
this.render()
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
this.innerHTML = this.template
|
||||
}
|
||||
render() {
|
||||
this.innerHTML = this.template;
|
||||
}
|
||||
}
|
|
@ -9,14 +9,14 @@ export class HelloWorld extends WebComponent {
|
|||
return ["name", "emotion"];
|
||||
}
|
||||
|
||||
onChanges({ previousValue, currentValue }) {
|
||||
console.log(">>> changed", { previousValue, currentValue });
|
||||
}
|
||||
|
||||
get template() {
|
||||
return `
|
||||
<h1>Hello ${this.name}${
|
||||
this.emotion === 'sad'
|
||||
? '. 😭'
|
||||
: '! 🙌'
|
||||
}</h1>`
|
||||
<h1>Hello ${this.name}${this.emotion === "sad" ? ". 😭" : "! 🙌"}</h1>`;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('hello-world', HelloWorld);
|
||||
customElements.define("hello-world", HelloWorld);
|
||||
|
|
Loading…
Reference in a new issue