-
Notifications
You must be signed in to change notification settings - Fork 0
/
双向绑定.html
48 lines (45 loc) · 1.07 KB
/
双向绑定.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>双向绑定</title>
</head>
<body>
<script>
class DataModel {
constructor(str = '') {
this.data = str;
this.nodes = [];
}
bindTo(node) {
this.nodes.push(node);
this.update();
}
update() {
const INPUT_NODE = ['INPUT', 'TEXTAREA'];
let {
nodes
} = this;
for (let i = 0, node; node = nodes[i++];) {
if (INPUT_NODE.includes(node.nodeName)) {
if (node.value !== this.data) { //避免光标跳到尾部
node.value = this.data;
}
} else {
node.textContent = this.data;
}
}
}
set(str) {
if (str !== this.value) {
this.data = str;
this.update();
}
}
get() {
return this.data;
}
}
</script>
</body>
</html>