美文网首页web前端
vue源码分析(七):监听者Watcher

vue源码分析(七):监听者Watcher

作者: 姜治宇 | 来源:发表于2020-09-05 09:09 被阅读0次

    上回我们留下了一个问题:
    当更新视图时,我们注册的key,跟触发时的key不一致了,所以导致无法更新视图,怎么办呢?
    我们知道,get和set的key肯定是一致的,那我们不妨在get和set里面注册和触发函数好了,这样key的问题就解决了,但新的问题又来了:

    function Vue(options){
        this.$options = options
        var data = this._data = this.$options.data
        //数据代理
        Object.keys(data).forEach(key=>{
            this._proxy(key)
        })
    
        //数据劫持
        observe(data)
    
        //模板解析
        this.$compile = new Compile(options.el,this) //模板解析
    }
    Vue.prototype = {
        _proxy(key){
            Object.defineProperty(this,key,{
                configurable:false,
                enumerable:true,
                get(){
                    return this._data[key]
                },
                set(newVal){
                    this._data[key] = newVal
                }
            })
        }
    }
    
    function Compile(el,vm){
        this.$vm = vm
        this.$el = document.querySelector(el)
    
        if(this.$el){
            this.$fragment = this.node2Fragment(this.$el) //将节点转到fragment处理
    
            this.init() //开始处理
    
            this.$el.appendChild(this.$fragment) //塞回原位
        }
    }
    Compile.prototype = {
        //将#app里面的节点都转到文档碎片中
        node2Fragment(el){
            var fragment = document.createDocumentFragment()
            var child = null
            while(child = el.firstChild) {
                fragment.appendChild(child)
            }
            return fragment
        },
        //处理碎片中的信息
        init(){
            this.compileElement(this.$fragment)
        },
        //正则匹配
        compileElement(el){
            var childNodes = el.childNodes;
            [].slice.call(childNodes).forEach(node=>{
                var text = node.textContent // 获取文本信息
                var reg = /\{\{(.*)\}\}/
                //这里增加指令的处理
                if(node.nodeType === 1){
                    //如果是元素节点
                    this.compile(node)
                } else if(node.nodeType === 3 && reg.test(text)) {
    
                    this.compileText(node,RegExp.$1) //更新视图动作
    
    
                    //订阅更新视图函数
                    /*
                    dep.register(RegExp.$1,()=>{ //注册的是key是a.b
                        //如果data发生了变化,需要再次调用this.compileText这个函数来更新视图
                        this.compileText(node,RegExp.$1)
                    })
                    */
    
                    //不直接订阅了,那应该咋更新视图呢?
    
    
    
                } else if(node.childNodes && node.childNodes.length) {
                    //递归
                    this.compileElement(node)
                }
            })
        },
        //处理元素节点
        compile(node){
            var nodeAttrs = node.attributes; // 获取元素节点的所有属性,伪数组
            [].slice.call(nodeAttrs).forEach(attr=>{
                var attrName = attr.name;//获取属性名
                if(attrName.indexOf('v-') === 0){//判断是否是指令
                    var exp = attr.value; //获取属性值,也就是触发的方法名
                    var dir = attrName.substring(2) // 截取字符串,得到on:click
                    if(dir.indexOf('on') === 0){ //判断事件指令
                        var eventType = dir.split(':')[1]; //获取事件类型
                        var fn = this.$vm.$options.methods && this.$vm.$options.methods[exp];// 获取函数
                        if(eventType && fn) {
                            node.addEventListener(eventType,fn.bind(this.$vm),false) // 注意fn里面的this指向
                        }
    
    
    
                    } else if(dir.indexOf('bind') === 0) { // 一般指令
                        var dirType = dir.split(':')[1] // 获取指令类型class
                        if(dirType === 'class') {
                            var oldClassName = node.className; //原来的class类
                            var newClassName = '' //动态class类
                            var classObj = eval('(' + exp + ')'); //解析为object对象
    
                            for(var key in classObj) { //遍历对象,如果value为true追加class名,false不追加
                                if(classObj[key]) {
                                    newClassName += ' ' + key
                                }
                            }
                            node.className = oldClassName + newClassName // 设置className
                        }
    
                    }
                    node.removeAttribute(attrName) // 从chrome控制台的Elements看文档结构,发现没有v-这样的属性(指令),所以需要处理完去掉
                }
            })
    
        },
    //用vm.data信息,替换大括号的name
        compileText(node,exp){
            console.log('最新值是:',this.getVMVal(exp))
            node.textContent = this.getVMVal(exp)
        },
    //处理层级问题
        getVMVal(exp){ // a.b.c
            var val = this.$vm._data
            var arr = exp.split('.') //["a", "b", "c"]
            arr.forEach(k=>{
                //debugger
                val = val[k] // 层级递进
            })
            return val
        }
    }
    
    //新增部分
    function observe(data){
        //对data进行defineProperty处理,嵌套的数据要用递归
        if(!data || typeof data!=='object'){//递归的退出条件
            return;
        }
    
        Object.keys(data).forEach(key=>{
            defineReactive(data,key,data[key])//对data里面的每一个key进行定义
        })
    
    }
    
    function defineReactive(data,key,val){
        var dep = new Dep()
        observe(val)//先执行递归,确保嵌套对象的key都可以被定义
        Object.defineProperty(data,key,{
            enumerable:true,
            configurable:false,
            get(){
                console.log('get操作:',key,'===>',val)
                dep.register(key,()=>{
                    console.log('更新操作')
                })
                return val
            },
            set(newVal){
                console.log('set操作:',key,'===>',newVal)
                val = newVal //修改为最新值
                //触发更新视图函数
                dep.emit(key) // 这里的key是b,而不是a.b
            }
        })
    }
    //引入观察订阅模式
    function Dep(){
        this.subs = {}
    }
    
    Dep.prototype.register = function (key, callback) {
    
        this.subs[key] = callback
    }
    Dep.prototype.emit = function (key) {
        console.log(key)
        this.subs[key]()
    
    }
    
    

    这个问题比较头大,我们可以引入一个新的监听对象——Watcher。
    Watcher的作用就是监听,回忆一下vue的watch用法:

    watch('a.b',function(oldVal,newVal){
        ...
    })
    

    说一下思路:
    1、在模板解析时,我们将正则匹配出来的大括号表达式都new一个Watcher实例对象。
    比如现在有{{name}}和{{a.b}}两个表达式,那就是new了2个Watcher,每个Watcher的回调函数,就是更新视图的操作。

    //引入watcher对象
                    new Watcher(this.$vm,RegExp.$1,(newVal,oldVal)=>{
                        if(newVal !== oldVal) {
    
                            node.textContent = newVal //更新视图操作
                        }
                    })
    

    2、在new Watcher的时候,触发defineProperty里面的get函数。

    function Watcher(vm,exp,cb){
        this.vm = vm; //vue对象
        this.exp = exp; //正则匹配的大括号表达式
        this.cb = cb; // 回调函数,也就是待执行的更新视图操作
        //主要是这一步
        this.value = this.getValue() //在new Watcher就调用,触发defineProperty里面的get
    }
    Watcher.prototype.getValue = function(){
        Dep.target = this //Dep.target是一个临时变量,this就是Watcher实例对象
        var newVal = this.getVMVal() //获取data的属性值,会触发get函数
        Dep.target = null
        return newVal
    }
    Watcher.prototype.getVMVal = function(){
        var val = this.vm._data
        if(this.exp.indexOf('.') !== -1) {
            var arr = this.exp.split('.') //["a", "b", "c"]
            arr.forEach(k=>{
                //debugger
                val = val[k] // 层级递进
            })
            return val
        } else {
            return val[this.exp]
        }
    
    }
    

    3、defineProperty里面的get函数,订阅Watcher实例对象,其实就是往dep的容器里面丢一个Watcher实例。

        Object.defineProperty(data,key,{
            enumerable:true,
            configurable:false,
            get(){
                console.log('get操作:',key,'===>',val)
                /*
                dep.register(key,()=>{
                    console.log('更新操作')
                })
                 */
                if(Dep.target) { //如果Dep.target有了Watcher,就存入到dep的容器里面
                    dep.register(Dep.target)
                }
                return val
            }
        })
    

    4、在触发data某个属性修改时,因为已经注册了这个属性的Watcher(容器里面有了这个Watcher对象),这时就遍历容器,执行每个Watcher里面的回调函数,也就是触发更新视图操作。

        Object.defineProperty(data,key,{
            enumerable:true,
            configurable:false,
            set(newVal){
                console.log('set操作:',key,'===>',newVal)
                val = newVal //修改为最新值
               
                dep.emit(key)
            }
        })
    

    5、观察订阅者就需要修改一下了,容器改为数组,订阅的是Watcher对象。

    //引入观察订阅模式
    function Dep(){
        this.subs = [] //容器,
    }
    Dep.prototype.register = function (obj) {
    
        if(Dep.target){
            this.subs.push(obj) //丢入容器的是Watcher对象,在Watcher实例化的时候丢入
        }
    }
    
    Dep.prototype.emit = function () {
    
        this.subs.forEach(obj=>{ //将容器中的Watcher对象遍历,顺序执行
            obj.update()
        })
    
    }
    

    这块确实有点绕,我们再捋一下。
    首先我们直接用观察订阅模式,发现嵌套对象的key无法匹配的问题,所以我们就直接放弃key-value的订阅方式,改为使用Watcher对象来处理,这样订阅的就是Watcher;而Watcher要跟观察者Dep发生联系,关键在于在new Watcher的时候,需要触发defineProperty函数里面的get,因为我们在get函数订阅了Watcher;这样一来,当每次触发set的时候,就可以从dep的容器里面取出Watcher,执行里面的回调函数了,回调函数的作用就是更新视图。
    把最终代码贴上来:

    function Vue(options){
        this.$options = options
        var data = this._data = this.$options.data
        //数据代理
        Object.keys(data).forEach(key=>{
            this._proxy(key)
        })
    
        //数据劫持
        observe(data)
    
        //模板解析
        this.$compile = new Compile(options.el,this) //模板解析
    }
    Vue.prototype = {
        _proxy(key){
            Object.defineProperty(this,key,{
                configurable:false,
                enumerable:true,
                get(){
                    return this._data[key]
                },
                set(newVal){
                    this._data[key] = newVal
                }
            })
        }
    }
    
    function Compile(el,vm){
        this.$vm = vm
        this.$el = document.querySelector(el)
    
        if(this.$el){
            this.$fragment = this.node2Fragment(this.$el) //将节点转到fragment处理
    
            this.init() //开始处理
    
            this.$el.appendChild(this.$fragment) //塞回原位
        }
    }
    Compile.prototype = {
        //将#app里面的节点都转到文档碎片中
        node2Fragment(el){
            var fragment = document.createDocumentFragment()
            var child = null
            while(child = el.firstChild) {
                fragment.appendChild(child)
            }
            return fragment
        },
        //处理碎片中的信息
        init(){
            this.compileElement(this.$fragment)
        },
        //正则匹配
        compileElement(el){
            var childNodes = el.childNodes;
            [].slice.call(childNodes).forEach(node=>{
                var text = node.textContent // 获取文本信息
                var reg = /\{\{(.*)\}\}/
                //这里增加指令的处理
                if(node.nodeType === 1){
                    //如果是元素节点
                    this.compile(node)
                } else if(node.nodeType === 3 && reg.test(text)) {
    
                    this.compileText(node,RegExp.$1) //更新视图动作
    
    
                    //订阅更新视图函数
                    /*
                    dep.register(RegExp.$1,()=>{ //注册的是key是a.b
                        //如果data发生了变化,需要再次调用this.compileText这个函数来更新视图
                        this.compileText(node,RegExp.$1)
                    })
                    */
    
                    //引入watcher对象
                    new Watcher(this.$vm,RegExp.$1,(newVal,oldVal)=>{ //this.cb.call(this.vm,newVal,oldVal)//更新视图操作
                        if(newVal !== oldVal) {
    
                            node.textContent = newVal //更新为最新值
                        }
                    })
    
    
    
                }
                if(node.childNodes && node.childNodes.length) {
                    //递归
                    this.compileElement(node)
                }
            })
        },
        //处理元素节点
        compile(node){
            var nodeAttrs = node.attributes; // 获取元素节点的所有属性,伪数组
            [].slice.call(nodeAttrs).forEach(attr=>{
                var attrName = attr.name;//获取属性名
                if(attrName.indexOf('v-') === 0){//判断是否是指令
                    var exp = attr.value; //获取属性值,也就是触发的方法名
                    var dir = attrName.substring(2) // 截取字符串,得到on:click
                    if(dir.indexOf('on') === 0){ //判断事件指令
                        var eventType = dir.split(':')[1]; //获取事件类型
                        var fn = this.$vm.$options.methods && this.$vm.$options.methods[exp];// 获取函数
                        if(eventType && fn) {
                            node.addEventListener(eventType,fn.bind(this.$vm),false) // 注意fn里面的this指向
                        }
    
    
    
                    } else if(dir.indexOf('bind') === 0) { // 一般指令
                        var dirType = dir.split(':')[1] // 获取指令类型class
                        if(dirType === 'class') {
                            var oldClassName = node.className; //原来的class类
                            var newClassName = '' //动态class类
                            var classObj = eval('(' + exp + ')'); //解析为object对象
    
                            for(var key in classObj) { //遍历对象,如果value为true追加class名,false不追加
                                if(classObj[key]) {
                                    newClassName += ' ' + key
                                }
                            }
                            node.className = oldClassName + newClassName // 设置className
                        }
    
                    }
                    node.removeAttribute(attrName) // 从chrome控制台的Elements看文档结构,发现没有v-这样的属性(指令),所以需要处理完去掉
                }
            })
    
        },
    //用vm.data信息,替换大括号的name
        compileText(node,exp){
            node.textContent = this.getVMVal(exp)
        },
    //处理层级问题
        getVMVal(exp){ // a.b.c
            var val = this.$vm._data
            if(exp.indexOf('.') !== -1) {
                var arr = exp.split('.') //["a", "b", "c"]
                arr.forEach(k=>{
                    //debugger
                    val = val[k] // 层级递进
                })
                return val
            } else {
                return val[exp]
            }
    
        }
    }
    
    //新增部分
    function observe(data){
        //对data进行defineProperty处理,嵌套的数据要用递归
        if(!data || typeof data!=='object'){//递归的退出条件
            return;
        }
    
        Object.keys(data).forEach(key=>{
            defineReactive(data,key,data[key])//对data里面的每一个key进行定义
        })
    
    }
    
    function defineReactive(data,key,val){
        var dep = new Dep()
        observe(val)//先执行递归,确保嵌套对象的key都可以被定义
        Object.defineProperty(data,key,{
            enumerable:true,
            configurable:false,
            get(){
                console.log('get操作:',key,'===>',val)
                /*
                dep.register(key,()=>{
                    console.log('更新操作')
                })
                 */
                if(Dep.target) { //如果Dep.target有了Watcher,就存入到dep的容器里面
                    dep.register(Dep.target)
                }
                return val
            },
            set(newVal){
                console.log('set操作:',key,'===>',newVal)
                val = newVal //修改为最新值
                //触发更新视图函数
                dep.emit(key) // 这里的key是b,而不是a.b
            }
        })
    }
    //引入Watcher
    function Watcher(vm,exp,cb){
        this.vm = vm; //vue对象
        this.exp = exp; //正则匹配的大括号表达式
        this.cb = cb; // 回调函数,也就是待执行的更新视图操作
        this.value = this.getValue() //在初始化的时候调用,触发defineProperty里面的get
    }
    Watcher.prototype.getValue = function(){
        Dep.target = this //Dep.target是一个临时变量
        var newVal = this.getVMVal()
        Dep.target = null
        return newVal
    }
    
    Watcher.prototype.getVMVal = function(){
        var val = this.vm._data
        if(this.exp.indexOf('.') !== -1) {
            var arr = this.exp.split('.') //["a", "b", "c"]
            arr.forEach(k=>{
                //debugger
                val = val[k] // 层级递进
            })
            return val
        } else {
            return val[this.exp]
        }
    
    }
    
    Watcher.prototype.update = function(){
        //获取新值
        let newVal = this.getValue()//这里会触发defineProperty的get
        let oldVal = this.value
        if(newVal !== oldVal){
            this.value = newVal
            this.cb.call(this.vm,newVal,oldVal)//更新视图操作
        }
    
    }
    
    //引入观察订阅模式
    function Dep(){
        this.subs = [] //容器,
    }
    Dep.prototype.register = function (obj) {
    
        if(Dep.target){
            this.subs.push(obj) //丢入容器的是Watcher对象,在Watcher实例化的时候丢入
        }
    }
    
    Dep.prototype.emit = function () {
    
        this.subs.forEach(obj=>{ //将容器中的Watcher对象遍历,顺序执行
            obj.update()
        })
    
    }
    
    

    做一下测试:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <div id="app">
        <p>{{name}}</p>
        <p>{{a.b}}</p>
        <button v-on:click="changeName">点击修改</button>
    </div>
    </body>
    </html>
    <script src="./myvue.js"></script>
    
    <script>
        const vm = new Vue({
            el:'#app',
            data:{
                name:'jack',
                a:{
                    b:'嵌套对象'
                }
            },
            methods:{
                changeName(){
                    this.name = 'tom'
                    this.a.b = '修改成功'
                }
            }
        })
    
    </script>
    
    
    大家再对照一下原理图,看是不是都理解了。 原理图.png

    相关文章

      网友评论

        本文标题:vue源码分析(七):监听者Watcher

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