有一个对象,是观察者,它用于观察另外一个对象的属性值变化,当属性值变化后会收到一个通知,可能会做一些事。
使用Object.defineProperty实现
<div id="container">
</div>
<script>
//创建一个观察者
function observer(target) {
const div = document.getElementById("container");
const ob = {};
const props = Object.keys(target);
for (const prop of props) {
Object.defineProperty(ob, prop, {
get() {
return target[prop];
},
set(val) {
target[prop] = val;
render();
},
enumerable: true
})
}
render();
function render() {
let html = "";
for (const prop of Object.keys(ob)) {
html += `
<p><span>${prop}:</span><span>${ob[prop]}</span></p>
`;
}
div.innerHTML = html;
}
return ob;
}
const target = {
a: 1,
b: 2
}
const obj = observer(target)
</script>
使用 Proxy
<div id="container">
</div>
<script>
//创建一个观察者
function observer(target) {
const div = document.getElementById("container");
const proxy = new Proxy(target, {
set(target, prop, value) {
Reflect.set(target, prop, value);
render();
},
get(target, prop){
return Reflect.get(target, prop);
}
})
render();
function render() {
let html = "";
for (const prop of Object.keys(target)) {
html += `
<p><span>${prop}:</span><span>${target[prop]}</span></p>
`;
}
div.innerHTML = html;
}
return proxy;
}
const target = {
a: 1,
b: 2
}
const obj = observer(target)
</script>