-
Notifications
You must be signed in to change notification settings - Fork 10
/
alpine.js
72 lines (58 loc) · 1.75 KB
/
alpine.js
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
window.Alpine = {
directives: {
'x-text': (el, value) => {
el.innerText = value
},
'x-show': (el, value) => {
el.style.display = value ? 'block' : 'none'
},
},
start() {
this.root = document.querySelector('[x-data]')
this.rawData = this.getInitialData()
this.data = this.observe(this.rawData)
this.registerListeners()
this.refreshDom()
},
registerListeners() {
this.walkDom(this.root, el => {
Array.from(el.attributes).forEach(attribute => {
if (! attribute.name.startsWith('@')) return
let event = attribute.name.replace('@', '')
el.addEventListener(event, () => {
eval(`with (this.data) { (${attribute.value}) }`)
})
})
})
},
observe(data) {
var self = this
return new Proxy(data, {
set(target, key, value) {
target[key] = value
self.refreshDom()
}
})
},
refreshDom() {
this.walkDom(this.root, el => {
Array.from(el.attributes).forEach(attribute => {
if (! Object.keys(this.directives).includes(attribute.name)) return
this.directives[attribute.name](el, eval(`with (this.data) { (${attribute.value}) }`))
})
})
},
walkDom(el, callback) {
callback(el)
el = el.firstElementChild
while (el) {
this.walkDom(el, callback)
el = el.nextElementSibling
}
},
getInitialData() {
let dataString = this.root.getAttribute('x-data')
return eval(`(${dataString})`)
}
}
window.Alpine.start()