-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcounter.htm
76 lines (66 loc) · 2.11 KB
/
counter.htm
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<template id="counter">
<style>
.counter {
display: flex;
width: 200px;
}
.count {
font-size: 2rem;
margin-right: 20px;
}
button {
height: 2rem;
margin-right: 10px;
width: 2rem;
}
</style>
<div class="counter">
<div class="count">0</div>
<button id="decrement">-</button><button id="increment">+</button>
</div>
</template>
<script>
class CounterComponent extends HTMLElement {
static get observedAttributes() { return ['count']; }
constructor() {
super();
const template = document.getElementById('counter');
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
connectedCallback() {
this.shadowRoot.querySelector('#increment').addEventListener('click', this.increment.bind(this));
this.shadowRoot.querySelector('#decrement').addEventListener('click', this.decrement.bind(this));
}
disconnectedCallback() {
this.shadowRoot.querySelector('#increment').removeEventListener('click', this.increment.bind(this));
this.shadowRoot.querySelector('#decrement').removeEventListener('click', this.decrement.bind(this));
}
attributeChangedCallback(name, oldValue, newValue) {
this.shadowRoot.querySelector('.count').innerHTML = newValue;
console.log(`${name} changed from ${oldValue} to ${newValue}`);
}
increment() {
this.setAttribute('count', parseInt(this.getAttribute('count'), 10) + 1);
}
decrement() {
const count = parseInt(this.getAttribute('count'), 10);
if (count !== 0) {
this.setAttribute('count', count - 1);
}
}
}
customElements.define('count-er', CounterComponent);
</script>
<count-er count="0"></count-er>
</body>
</html>