-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (69 loc) · 1.82 KB
/
index.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
78
79
80
81
82
83
84
/**
* 1. 数据 -> 响应式数据 Object.defineProperty Proxy
* 2. input -> input/keyup -> 事件处理函数的绑定 -> 改变数据
* 3. 相关的dom -> 数据 => 绑定在一起
* 操作数据的某个属性 -> 对应DOM就改变
*
*/
const reg_var = /\{\{(.+?)\}\}/;
class MVVM {
constructor(el, data) {
this.el = document.querySelector(el);
this.data = data;
this.domPool = {};
this.init();
}
init() {
this.initData();
this.initDom();
}
initDom() {
this.bindDom(this.el);
this.bindInput(this.el);
}
initData() {
const _this = this;
this.data = new Proxy(this.data, {
get(target, key) {
console.log('target', target);
return Reflect.get(target, key);
},
set(target, key, value) {
_this.domPool[key].innerText = value;
return Reflect.set(target, key, value);
}
});
}
bindDom(el) {
const childNodes = el.childNodes;
childNodes.forEach(item => {
if (item.nodeType === 3) {
const _value = item.nodeValue;
if (_value.trim().length) {
let _isValid = reg_var.test(_value);
if (_isValid) {
const _key = _value.match(reg_var)[1].trim();
this.domPool[_key] = item.parentNode;
item.parentNode.innerText = this.data[_key] || undefined;
}
}
}
item.childNodes && this.bindDom(item);
});
}
bindInput(el) {
const _allInputs = el.querySelectorAll('input');
_allInputs.forEach(input => {
const _vModel = input.getAttribute('v-model');
if (_vModel) {
input.addEventListener('keyup', this.handleInput.bind(this, _vModel, input), false);
}
});
}
handleInput(key, input) {
this.data[key] = input.value;
}
setData(key, value) {
this.data[key] = value;
}
}