// html
<span id="box">
<h1 id='text'></h1>
<input type="text" id='input' oninput="inputChange(event)" />
<button id="button" onclick="clickChange()">Click me</button>
</span>
const input = document.getElementById('input');
const text = document.getElementById('text');
const button = document.getElementById('button');
const data = {
value: ''
}
// 使用defineProperty
function defineProperty(obj, attr) {
let val
Object.defineProperty(obj, attr, {
set(newValue) {
if (val === newValue) {
return;
}
val = newValue;
input.value = newValue;
text.innerHTML = newValue;
},
get() {
return val
}
})
}
defineProperty(data, 'value')
function inputChange(event) {
data.value = event.target.value
}
function clickChange() {
data.value = 'hello'
}
// 使用proxy
let handler = {
get: function (obj, name) {
return name in obj ? obj[name] : '';
},
set: function (obj, name, value) {
obj[name] = value;
text.innerHTML = value;
input.value = value;
},
};
let p = new Proxy(data, handler);
function inputChange(event) {
p.value = event.target.value
}
function clickChange() {
p.value = 'hello'
}