refactor(site, templates): use HTMLElement.dataset

This commit is contained in:
Ayo 2023-11-17 20:28:59 +01:00
parent b4c7bab3df
commit ac1e839ca4
5 changed files with 9 additions and 29 deletions

View file

@ -7,13 +7,11 @@ class HelloWorld extends WebComponent {
onInit() {
let count = 0;
this.onclick = () => {
this.setAttribute("data-name", `Clicked ${++count}x`);
};
this.setAttribute("title", "Click me please");
this.dataset.name = this.dataset.name ?? 'World';
this.onclick = () => this.dataset.name = `Clicked ${++count}x`;
}
get template() {
return `<button style="cursor:pointer">Hello ${this.dataName}!</button>`;
return `<button style="cursor:pointer">Hello ${this.dataset.name}!</button>`;
}
}

View file

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

View file

@ -3,28 +3,18 @@
* @see https://ayco.io/n/web-component-base
*/
class MyHelloWorld extends WebComponent {
// intialize props
dataName = 'World';
// tell browser which props to cause render
static properties = ["data-name"];
// Triggered when the component is connected to the DOM
onInit() {
let count = 0;
// initialize event handler
this.onclick = () => {
this.setAttribute("data-name", `Clicked ${++count}x`);
};
this.dataset.name = this.dataset.name ?? 'World';
this.onclick = () => this.dataset.name = `Clicked ${++count}x`
}
// give readonly template
get template() {
/**
* any attribute/property in kebab-case...
* can be accessed via its camelCase counterpart
* example: data-name prop is accessible as this.dataName
*/
return `<button style="cursor:pointer">Hello ${this.dataName}!</button>`;
return `<button style="cursor:pointer">Hello ${this.dataset.name}!</button>`;
}
}

View file

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

View file

@ -25,7 +25,7 @@
<main>
<h2>Welcome to {{ project.name }}</h2>
<p>
Here's a vanilla custom element: <vanilla-hello-world/>
Here's a vanilla custom element: <my-hello-world />
</p>
<code-block language="js">
class HelloWorld extends HTMLElement {