refactor(template): different prop access examples

- HTMLElement.dataset for vanilla
- WebComponent camelCase counterpart for custom base
This commit is contained in:
Ayo 2023-11-17 20:53:51 +01:00
parent 5d4702b1a6
commit 363f2f9201
2 changed files with 9 additions and 3 deletions

View file

@ -3,18 +3,20 @@
* @see https://ayco.io/n/web-component-base * @see https://ayco.io/n/web-component-base
*/ */
class MyHelloWorld extends WebComponent { class MyHelloWorld extends WebComponent {
// initialize prop
dataName = 'World';
// tell browser which props to cause render // tell browser which props to cause render
static properties = ["data-name"]; static properties = ["data-name"];
// Triggered when the component is connected to the DOM // Triggered when the component is connected to the DOM
onInit() { onInit() {
let count = 0; let count = 0;
this.dataset.name = this.dataset.name ?? 'World';
this.onclick = () => this.dataset.name = `Clicked ${++count}x` this.onclick = () => this.dataset.name = `Clicked ${++count}x`
} }
// give readonly template // give readonly template
get template() { get template() {
return `<button style="cursor:pointer">Hello ${this.dataset.name}!</button>`; return `<button style="cursor:pointer">Hello ${this.dataName}!</button>`;
} }
} }

View file

@ -5,7 +5,11 @@ class HelloWorld extends HTMLElement {
connectedCallback() { connectedCallback() {
let count = 0; let count = 0;
this.dataset.name = this.dataset.name ?? 'World';
if (!('name' in this.dataset)) {
this.dataset.name = 'World';
}
this.onclick = () => this.dataset.name = `Clicked ${++count}x`; this.onclick = () => this.dataset.name = `Clicked ${++count}x`;
} }