
最简单的双向数据绑定的实现,开始通过使用Object.defineProperty(),到ES6新增的Proxy的实现。
HTML
1 2 3 4
|
<div id="app"> <input type="text" id="inputTxt"> <input type="text" id="showTxt"> </div>
|
1 2 3 4 5 6 7 8 9 10 11 12 13
|
var obj = {}; Object.defineProperty(obj, 'txt', { get: () { return obj; }, set: function (newValue) { document.getElementById('inputTxt').value = newValue; document.getElementById('showTxt').value = newValue; } }) document.addEventListener('keydown', function (e) { obj.txt = e.target.value; })
|
Proxy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
const obj = {}; const aProxy = new Proxy(obj, { get: function(target, key, receiver){ return Reflect.get(target, key, receiver); }, set: function (target, key, value, receiver) { if(key === 'txt' && value !== undefined) { document.getElementById('inputTxt').value = value; document.getElementById('showTxt').value = value; } return Reflect.set(target, key, value, receiver); } }); document.addEventListener('keydown', function (e) { aProxy.txt = e.target.value; })
|
近期评论