SOURCE

console 命令行工具 X clear

                    
>
console
class Dep {
    constructor(){
        this.subs = []
    }

    addSub(sub){
        this.subs.push(sub)
    }

    removeSub(sub){
        remove(this.subs, sub)
    }

    depend(){
        if(window.target){
            this.addSub(window.target)
        }
    }

    notify(){
        const subs = this.subs.slice()
        for(let i=0; i< this.subs.length; i++){
            subs[i].update()
        }
    }
}

function remove(arr, item){
    if(arr.length){
        const index = arr.indexOf(item)
        if(index > -1){
            return arr.splice(index, 1)
        }
    }
}

// 每个key都有一个数组,用来存储当前key的依赖。
// 假设依赖是一个函数,保存在window.target上
function defineReactive(data, key, val){
    let dep = new Dep()
    Object.defineProperty(data, key, {
        enumerable: true,
        configurable: true,
        get: function(){
            // dep.push(window.target)
            dep.depend()
            return val
        },
        set: function(newVal){
            if(val == newVal){
                return 
            }
            // for(let i=0; i<dep.length; i++){
            //     dep[i](newVal, val)
            // }
            dep.notify()
            val = newVal
        }
    })
}
<html>
    <head>

    </head>
    <body>
        <p>Object的变化侦测</p>
    </body>
</html>