-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathSecondsCounter.ts
67 lines (55 loc) · 1.96 KB
/
SecondsCounter.ts
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
import {setInterval} from '../node_modules/ecmassembly/assembly/setInterval'
import {customElements, HTMLElement, ShadowRootInit} from '../node_modules/asdom/assembly/index'
import {log} from './imports'
let count: i32 = 0
const elements: SecondsCounter[] = []
setInterval(() => {
count++
for (let i = 0, l = elements.length; i < l; i++) elements[i].update()
}, 1000)
export class SecondsCounter extends HTMLElement {
static observedAttributes: string[] = ['some-attribute']
// count: i32 = 0
constructor() {
super()
log('AS: <seconds-counter> constructed')
}
connectedCallback(): void {
log('AS: <seconds-counter> connected')
elements.push(this)
if (!this.shadowRoot) this.attachShadow({mode: 'open'} as ShadowRootInit)
this.shadowRoot!.innerHTML = this.template()
this.countOutput = this.shadowRoot!.querySelector('strong') as HTMLElement
}
disconnectedCallback(): void {
log('AS: <seconds-counter> disconnected')
elements.splice(elements.indexOf(this), 1)
}
attributeChangedCallback(name: string, oldVal: string | null, newVal: string | null): void {
if (newVal == 'bar') {
log('AS: some-attribute has a bar value!')
} else {
log('AS: some-attribute has some other value!')
}
}
countOutput: HTMLElement | null = null
template(): string {
return /*html*/ `
<style>
:host { display: block; }
.content { padding: 3px; color: white; background: deeppink; }
</style>
<span>
I am a custom <seconds-counter> element. The seconds count is <strong>${count}</strong>!
${this.childNodes.length ? /*html*/ `Distributed content: <span class="content"><slot></slot></span>` : ''}
</span>
`
}
update(): void {
this.countOutput!.innerText = count.toString()
}
}
// The customElements.define call has to be slightly different in
// AssemblyScript because AS does not yet support constructor function
// references.
customElements.define('seconds-counter', () => new SecondsCounter(), SecondsCounter.observedAttributes)