美文网首页
Proxy实现观察者模式

Proxy实现观察者模式

作者: Chris__Liu | 来源:发表于2020-04-03 15:17 被阅读0次

代理对象情况

 let o = new Proxy({ a: 1, b: 2 }, {
            get(obj,prop) { return obj[prop]; },
            set(obj,prop,newValue) {
                document.querySelector('#data').innerText = newValue
                val = newValue;
            },

        })
        document.querySelector('#input').addEventListener('input', (e) => {
            o.a = e.target.value
        })

proxy 可以代理数组,完成响应式,这是defineproperty做不到的

let o = new Proxy([1,2,3,4], {
            get(obj,prop) { return obj[prop]; },
            set(obj,prop,newValue) {
                console.log(obj,prop)
                document.querySelector('#data').innerText = newValue
                val = newValue;
            },

        })
        document.querySelector('#input').addEventListener('input', (e) => {
            o[3] = e.target.value
        })

相关文章

网友评论

      本文标题:Proxy实现观察者模式

      本文链接:https://www.haomeiwen.com/subject/fbghphtx.html