-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.html
63 lines (52 loc) · 1.64 KB
/
index.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
62
63
<html>
<div x-data="{ count: 0 }">
<button @click="count++">+</button>
<button @click="count--">-</button>
<span x-text="count"></span>
</div>
<script>
let root = document.querySelector('[x-data]')
let rawData = getInitialData()
let data = observe(rawData)
registerListeners()
refreshDom()
function registerListeners() {
walkDom(root, el => {
if (el.hasAttribute('@click')) {
let expression = el.getAttribute('@click')
el.addEventListener('click', () => {
eval(`with (data) { (${expression}) }`)
})
}
})
}
function observe(data) {
return new Proxy(data, {
set(target, key, value) {
target[key] = value
refreshDom()
}
})
}
function refreshDom() {
walkDom(root, el => {
if (el.hasAttribute('x-text')) {
let expression = el.getAttribute('x-text')
el.innerText = eval(`with (data) { (${expression}) }`)
}
})
}
function walkDom(el, callback) {
callback(el)
el = el.firstElementChild
while (el) {
walkDom(el, callback)
el = el.nextElementSibling
}
}
function getInitialData() {
let dataString = root.getAttribute('x-data')
return eval(`(${dataString})`)
}
</script>
</html>