双向绑定 🌕

概述

其实,双向绑定的实现就是Object.defineProperty的一种使用示例。

html

1
2
3
4
5
6
7
8
9
10
11
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>双向绑定</title>
</head>
<body>
<input id="a">
<p id="b"></p>
</body>
</html>

js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var $a = document.getElementById("a");
var $b = document.getElementById("b");
var obj = {};

Object.defineProperty(obj, "content", {
get: function() {
//console.log('get...')
},
set: function(val) {
$b.textContent = val;
//console.log('set...')
}
});

$a.addEventListener("input", function() {
obj.content = this.value;
});

// init
$a.value = $b.textContent = obj.content = "123";