手写vue简易响应式系统

143 阅读1分钟

        class Dep { // 发布订阅
            constructor() {
                this.subs = []

            }
            depend() {
                if (Dep.target && !this.subs.includes(Dep.target)) {
                    this.subs.push(Dep.target)

                }
            }
            notify() {
                this.subs.forEach(n => {
                    n.update()
                })
            }
        }
        class Watcher {
            constructor(target, prop, cb) {
                this.target = target;
                this.prop = prop;
                this.cb = cb;
                this.invoke()
            }
            update() {
                this.cb()
            }
            invoke() {
                Dep.target = this;
                this.target[this.prop]
                Dep.target = null

            }
        }

        function defReactive(obj, key, val) {
            const dep = new Dep()
            Object.defineProperty(obj, key, {
                enumerable: true,
                configurable: true,
                get: function () {
                    dep.depend();
                    return val
                },
                set: function (newVal) {
                    val = newVal
                    dep.notify()
                }
            })
        }
        // function watcher(action) {
        //     Dep.target = action
        //     Dep.target()
        //     Dep.target = null
        // }

        // watcher(() => {
        //     man.name = 'wenhao' + man.age
        // })
        function observe(ob) {
            // 只是浅层的监听,实际会递归整个对象
            Object.keys(ob).forEach(n => {
                defReactive(ob, n, ob[n])
            })
        }
        const man = { name: 'wenhao', age: 21, city: 'wuhan' }
        observe(man)
        new Watcher(man, 'name', function () {
            console.log(111111111, 'name')
        })
  
        man.name = 123
        man.name = 111
        man.name = 222
        man.name = 333