-
Notifications
You must be signed in to change notification settings - Fork 1
/
x-counter.html
61 lines (47 loc) · 2.13 KB
/
x-counter.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<!-- The "Single File Web Component" wrapper -->
<sfwc>
<!-- Component's template -->
<template>
<!-- Elements with an id are available on this.refs, e.g. this.refs.badge. See connectedCallback below. -->
<div class="bg-blue-light">Count <m-badge id="badge" count=""></m-badge></div>
<!-- Onevent attributes are replaced with working event listeners. See connectedCallback below. -->
<button onclick="clickHandler">Click me</button>
<!-- Component's styles -->
<style>
/* Importing global stylesheets will penetrate shadow DOM. Browsers use cached file if already downloaded. */
@import "https://unpkg.com/[email protected]/dist/m-min.css";
/* :host selects the custom element, i.e. <x-counter>, not the template. */
:host { display: block }
/* Anything else is scoped to this template. */
div { color: lightsalmon }
</style>
</template>
<!-- Component's script -->
<script type="module">
import {getTemplateRefs, bindTemplateEvents} from "./utils.js";
// Note the need for window.top if this is imported with an <object> element
window.top.customElements.define('x-counter', class extends HTMLElement {
// this.isConnected is not very helpful, CE needs this flag
#initialized = false;
// Try document.currentScript.previousElementSibling instead
#template = document.querySelector('template');
constructor() {
super();
this.attachShadow({ mode: 'open' }).appendChild(this.#template.content.cloneNode(true));
}
connectedCallback() {
if (!this.#initialized) {
// Replaces any onevent attributes in the template with working event listeners. See utils.js.
bindTemplateEvents(this);
// Set up refs, i.e. children with an id. Ids are safe because of shadow DOM. See utils.js.
this.refs = getTemplateRefs(this.shadowRoot);
this.#initialized = true;
}
}
clickHandler(e) {
const count = Number(this.refs.badge.getAttribute('count'));
this.refs.badge.setAttribute('count', count + 1);
}
})
</script>
</sfwc>