refactor(site): update vanilla observed attribute

This commit is contained in:
Ayo 2023-11-18 01:55:57 +01:00
parent 1c38ec8e1e
commit 2b0f85c2eb
2 changed files with 16 additions and 9 deletions

View file

@ -1,20 +1,21 @@
class HelloWorld extends HTMLElement { class HelloWorld extends HTMLElement {
static get observedAttributes() { static get observedAttributes() {
return ["data-name"]; return ["my-name"];
} }
connectedCallback() { connectedCallback() {
let count = 0; let count = 0;
const currentName = this.getAttribute('my-name');
if (!('name' in this.dataset)) { if (!currentName) {
this.dataset.name = 'World' this.setAttribute('my-name', 'World')
} }
this.onclick = () => this.dataset.name = `Clicked ${++count}x`; this.onclick = () => this.setAttribute("my-name", `Clicked ${++count}x`);
} }
attributeChangedCallback(property, previousValue, currentValue) { attributeChangedCallback(property, previousValue, currentValue) {
if (property === "data-name" && previousValue !== currentValue) { if (property === "my-name" && previousValue !== currentValue) {
this.innerHTML = `<button style="cursor:pointer">Hello ${currentValue}!</button>`; this.innerHTML = `<button style="cursor:pointer">Hello ${currentValue}!</button>`;
} }
} }

View file

@ -30,18 +30,24 @@
<code-block language="js"> <code-block language="js">
class HelloWorld extends HTMLElement { class HelloWorld extends HTMLElement {
static get observedAttributes() { static get observedAttributes() {
return [&quot;data-name&quot;]; return [&quot;my-name&quot;];
} }
connectedCallback() { connectedCallback() {
let count = 0; let count = 0;
const currentName = this.getAttribute(&quot;my-name&quot;);
if (!currentName) {
this.setAttribute(&quot;my-name&quot;, &quot;World&quot;)
}
this.onclick = () => { this.onclick = () => {
this.setAttribute(&quot;data-name&quot;, `Clicked ${++count}x`); this.setAttribute(&quot;my-name&quot;, `Clicked ${++count}x`);
}; };
} }
attributeChangedCallback(property, previousValue, currentValue) { attributeChangedCallback(property, previousValue, currentValue) {
if (property === &quot;data-name&quot; && previousValue !== currentValue) { if (property === &quot;my-name&quot; && previousValue !== currentValue) {
this.innerHTML = `&lt;button style=&quot;cursor:pointer&quot;&gt;Hello ${currentValue}!&lt;/button&gt;`; this.innerHTML = `&lt;button style=&quot;cursor:pointer&quot;&gt;Hello ${currentValue}!&lt;/button&gt;`;
} }
} }