-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path双向绑定.html
94 lines (85 loc) · 2.55 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
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
85
86
87
88
89
90
91
92
93
94
<!DOCTYPE html>
<html lang="zh-ch">
<head>
<meta charset="utf-8">
<title>观察者模式双向绑定</title>
</head>
<style> .parent {
display: table;
width: 300px;
height: 300px;
text-align: center;
border-collapse: collapse;
}
.row {
display: table-row;
}
.son {
display: table-cell;
height: 200px;
background-color: yellow;
vertical-align: middle;
}</style>
<body>
<div class="parent">
<div class="row">
<div class="son">会议认为,党的十八大以来,我国经济发展取得历史性成就、
</div>
<div class="son">会议认为,党的十八大以来,我国经济发展取得历史性成就、
</div>
</div>
<div class="row">
<div class="son">会议认为,党的十八大以来,我国经济发展取得历史性成就、
</div>
<div class="son">会议认为,党的十八大以来,我国经济发展取得历史性成就、
</div>
</div>
</div>
<input id='input' onchange="haddleChange()" />
<script type="text/javascript">
var obj = {};
window.obj = obj;
function haddleChange() {
obj.name = document.getElementById('input').value;
}
function observer(val) {
console.log('更新了:', val);
document.getElementById('input').value = val;
}
// 1.
Object.defineProperty(obj, 'name', {
get() {
return obj[name];
},
set(val) {
obj[name] = val;
observer(val);
}
});
obj.name = '小明1';
// 2.
class Person {
constructor() {
this.age = 22;
}
set name(val) {
observer(val);
}
get name() {
return this.name;
}
}
const obj2 = new Person();
obj2.name = '小明2';
// 3.
const obj3 = new Proxy({}, {
set(target, key, val, reciever) {
if (key === 'name') {
observer(val);
}
}
});
obj3.name = '小明3';
</script>
</body>
</html>