-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmvvm.js
77 lines (70 loc) · 1.61 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
function Mvvm(options = {}) {
this.$options = options
this._data = this.$options.data
observe(this._data)
for (let key in this._data) {
Object.defineProperty(this, key, {
enumerable: true,
get() {
return this._data[key]
},
set(newValue) {
this._data[key] = newValue
}
})
}
new Compile(options.el, this)
}
// 模板处理
function Compile(el, vm) {
vm.$el = document.querySelector(el)
let fragment = document.createDocumentFragment()
while(child = vm.$el.firstChild) {
fragment.appendChild(child)
}
replace(fragment)
function replace(fragment) {
Array.from(fragment.childNodes).forEach(note => {
let text = note.textContent
let reg = /\{\{(.*)\}\}/
if (note.nodeType === 3 && reg.test(text)) {
//console.log(RegExp.$1); // RegExp.$1 取出{{}}的值
let arr = RegExp.$1.split('.')
let val = vm
arr.forEach(item => {
val = val[item]
})
note.textContent = text.replace(reg, val)
}
if (note.childNodes) {
replace(note)
}
})
}
vm.$el.appendChild(fragment)
}
function Observe(data) {
for (const key in data) {
observe(key)
let val = data[key]
Object.defineProperty(data, key, {
enumerable: true,
get() {
return val
},
set(newVal) {
if (newVal === val) {
return
}
val = newVal
observe(newVal)
}
})
}
}
function observe(data) {
if (typeof data !== 'object') {
return
}
return new Observe(data)
}