文章原文:各種源碼實(shí)現(xiàn)
1.defineProperty 版本
//數(shù)據(jù)
const data = {
text:'default'
};
const input = document.getElementById('input');
const span = document.getElementById('span');
//數(shù)據(jù)劫持
Object.defineProperty(data, 'text', {
//數(shù)據(jù)變化 -->修改視圖
set(newVal) {
input.value = newVal;
span.innerHTML = newVal;
}
});
//視圖更改 --> 數(shù)據(jù)變化
input.addEventListener('keyup', function(e) {
data.text = e.target.value
})
2.proxy 版本
//數(shù)據(jù)
const data = {
text:'default'
};
const input = document.getElementById('input');
const span = document.getElementById('span');
//數(shù)據(jù)劫持
const handler = {
set(target, key, value) {
terget[key] = value;
//數(shù)據(jù)變化 --> 修改視圖
input.value = value;
span.innerHTML = value;
return value;
}
};
const proxy = new Proxy(data, handler);
//視圖更改 --> 數(shù)據(jù)變化
input.addEventListener('keyup',function(e) {
proxy.text = e.target.value;
})