Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 72a19aa

Browse files
committed
feat: enhance WebComponent with event dispatcher at state
1 parent 3a09890 commit 72a19aa

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

examples/browsers/web-component.mjs

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
class WebComponent extends HTMLElement {
1+
export class WebComponent extends HTMLElement {
2+
3+
static tagName = 'web-component';
4+
5+
static eventNames = {
6+
statechange: this.tagName + '.statechange'
7+
};
28

39
static htmlString = null;
410

@@ -21,7 +27,17 @@ class WebComponent extends HTMLElement {
2127
this.shadowRoot.adoptedStyleSheets.push(styles);
2228

2329
// state
24-
this.state = {};
30+
this.state = new Proxy({}, {
31+
set: (target, prop, value) => {
32+
target[prop] = value;
33+
const name = this.constructor.eventNames.statechange;
34+
const detail = { element: this, prop, value };
35+
const payload = { detail, bubbles: true, composed: true };
36+
const event = new CustomEvent(name, payload);
37+
this.dispatchEvent(event);
38+
return true;
39+
}
40+
});
2541
}
2642

2743
static get observedAttributes() {
@@ -49,6 +65,11 @@ class WebComponent extends HTMLElement {
4965
}
5066
}
5167

68+
/**
69+
* HTML template as string
70+
*
71+
* @type {string}
72+
*/
5273
WebComponent.htmlString = `
5374
<h1>
5475
<slot></slot>
@@ -58,6 +79,11 @@ WebComponent.htmlString = `
5879
</p>
5980
`;
6081

82+
/**
83+
* CSS styles as string
84+
*
85+
* @type {string}
86+
*/
6187
WebComponent.cssString = `
6288
:host {
6389
display: block;
@@ -80,5 +106,3 @@ WebComponent.cssString = `
80106
color: blue;
81107
}
82108
`;
83-
84-
customElements.define('web-component', WebComponent);

0 commit comments

Comments
 (0)