-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmvvm.js
53 lines (53 loc) · 1.75 KB
/
mvvm.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
class Vue {
constructor(opt) {
this.opt = opt
this.observe(opt.data)
let root = document.querySelector(opt.el)
this.compile(root)
}
// 为响应式对象 data 里的每一个 key 绑定一个观察者对象
observe(data) {
Object.keys(data).forEach(key => {
let obv = new Observer()
data["_" + key] = data[key]
// 通过 getter setter 暴露 for 循环中作用域下的 obv,闭包产生
Object.defineProperty(data, key, {
get() {
Observer.target && obv.addSubNode(Observer.target);
return data['_' + key]
},
set(newVal) {
obv.update(newVal)
data['_' + key] = newVal
}
})
})
}
// 初始化页面,遍历 DOM,收集每一个key变化时,随之调整的位置,以观察者方法存放起来
compile(node) {
[].forEach.call(node.childNodes, child => {
if (!child.firstElementChild && /\{\{(.*)\}\}/.test(child.innerHTML)) {
let key = RegExp.$1.trim()
child.innerHTML = child.innerHTML.replace(new RegExp('\\{\\{\\s*' + key + '\\s*\\}\\}', 'gm'), this.opt.data[key])
Observer.target = child
this.opt.data[key]
Observer.target = null
} else if (child.firstElementChild)
this.compile(child)
})
}
}
// 常规观察者类
class Observer {
constructor() {
this.subNode = []
}
addSubNode(node) {
this.subNode.push(node)
}
update(newVal) {
this.subNode.forEach(node => {
node.innerHTML = newVal
})
}
}