一、ECMAScript5 - Object.defineProperty
利用对象中的访问器属性,监听值的修改。
<input id="dInput" /> <p>值:<span id="pValue"></span></p> <script> const dInput = document.getElementById('dInput') const pValue = document.getElementById('pValue') const data = { inputValue: '' } Object.defineProperty(data, 'text', { get () { return this.inputValue }, set (value) { dInput.value = value this.inputValue = value // 展示结果 pValue.innerText = value } }) dInput.addEventListener('keyup', e => { data.text = e.target.value }) </script>
二、ECMAScript6 - Proxy
& Reflect
使用代理(Proxy)拦截对象值的修改操作。
<input id="pInput" /> <p>值:<span id="pValue"></span></p> <script> const pInput = document.getElementById('pInput') const pValue = document.getElementById('pValue') const targetData = { text: '' } const data = new Proxy(targetData, { set (trapTarget, key, value, receiver) { pInput.value = value pValue.innerText = value return Reflect.set(trapTarget, key, value, receiver) } }) pInput.addEventListener('keyup', e => { data.text = e.target.value }) </script>