双向绑定分析源码

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .top {
      margin-bottom: 50px;
    }
  </style>
</head>
<body>
  <div id="app">
    <div class="top">
      <div>作者:{{name}}</div>
      <input type="text" v-model="name" placeholder="输入名字"><span>{{name}}</span>
    </div>
    <div>
      <div>更多:{{more.like}}</div>
      <input type="text" v-model="more.like" placeholder="输入更多"><span>{{more.like}}</span>
    </div>
    
  </div>
 
  <script src="./vue.js"></script>
 
  <script>
    const vm = new Vue({
      el: '#app',
      data: {
        name: '梦里',
        more: {
          like: '篮球'
        },
      }
    })
    console.log(vm)
  </script>
</body>
</html>

vue.js

class Vue {
    constructor(obj_instance) {
      this.$data = obj_instance.data;
      //调用数据监听函数Observer
      Observer(this.$data)   //这一步执行的时候,所有数据的get()都会被触发
      Compile(obj_instance.el,this)  //模板解析器
    }
 }
  //数据劫持——监听实例里的数据
  function Observer(data_instance) {
    if(!data_instance || typeof data_instance !== 'object') return   //递归结束的出口
    //创建收集订阅者数组的实例
    const dependency = new Dependency()
    Object.keys(data_instance).forEach(key => {
      let value = data_instance[key];
   
      Observer(value);  //递归遍历所有子属性
      //使用Object.defineProperty()来对数据进行监听
      Object.defineProperty(data_instance,key,{
        enumerable: true,  //属性可枚举
        configurable: true,  //属性描述符可以被改变
        get() {
          Dependency.temp && dependency.addSub(Dependency.temp)  //向订阅者数组中添加订阅者
          return value
        },
        set(newValue) {
          value = newValue;
          Observer(newValue)  //如果不加,那么当给某个值设置的属性值为对象的时候那么这个对象就不会有getter和setter 
          dependency.notify()  //通知订阅者
        }
      })
    })
  }
   
   
  //HTML模板解析——替换DOM
  //添加订阅者,我的模版解析只需要解析一遍,因为解析一遍过后相应的
// 位置上就已经添加上订阅者了,所以当数据变化的时候订阅者就可以在相应的位置上做出更改
  function Compile(element,vm) {
    vm.$el = document.querySelector(element);
    //创建文档碎片之后一次性的挂载到页面上,速度更快
    let fragment = document.createDocumentFragment()
    let child;
   
    while(child = vm.$el.firstChild) {
      fragment.appendChild(child)
    }
    fragment_compile(fragment)
   
   
    //替换文档碎片内容
    function fragment_compile(node) {
      //正则表达式
      const pattern = /\{\{\s*(\S+)\s*\}\}/;
      //如果判断的结果为文本,那就进行这样的处理
      if(node.nodeType === 3) {  
        const xxx = node.nodeValue
        //匹配{{xxx}}的数据
        const result_regex= pattern.exec(node.nodeValue)
        if(result_regex) {
          const result = result_regex[1].split('.').reduce((acc,curr) => {
            return acc[curr]
          },vm.$data)
          //将{{}}去除也就是 {{name}} => 梦里,这个时候是替换文档内容的时候,也正是这个时候去创建订阅者
          node.nodeValue = xxx.replace(pattern,result)
          //创建订阅者,以后数据发生变化就会进行更新相应的节点
          new Watcher(vm,result_regex[1],newValue => {
            node.nodeValue = xxx.replace(pattern,newValue)
          })
        }
        return
      }
      //如果判断的结果为Input
      if(node.nodeType === 1 && node.nodeName === 'INPUT') {
        //获取节点的属性
        const attr = Array.from(node.attributes)
        attr.forEach(item => {
          if(item.nodeName === 'v-model') {
            const vaule = item.nodeValue.split('.').reduce((acc,curr) => {
              return acc[curr]
            },vm.$data)
            node.value = vaule
            //创建订阅者,这样以后数据发生变化的时候input框中的数据也会发生变化
            new Watcher(vm,item.nodeValue,newValue => {
              node.value = newValue
            })
            //添加input事件,为了实现试图改变的时候数据也改变
            node.addEventListener('input',e => {
              //['more','like']
              const arr1 = item.nodeValue.split('.')
              //['more','like'] => ['more']
              const arr2 = arr1.slice(0,arr1.length-1)
              const final = arr2.reduce((acc,curr) => acc[curr],vm.$data)
              final[arr1[arr1.length-1]] = e.target.value
            })
          }
        })
      }
      node.childNodes.forEach(child => fragment_compile(child))
    }
   
    //将文档碎片应用于页面
    vm.$el.appendChild(fragment)
  } 
   
   
  //依赖——收集和通知订阅者
  class Dependency {
    constructor() {
      //订阅者数组
      this.subscribers = []
    }
   
    //添加订阅者
    addSub(sub) {
      this.subscribers.push(sub)
    }
   
    //通知订阅者
    notify() {
      this.subscribers.forEach(sub => {
        sub.update()
      })
    }
  }
   
   
  //订阅者
  class Watcher {
    constructor(vm,key,callback) {
      this.vm = vm
      this.key = key
      this.callback = callback
      //临时属性
      Dependency.temp = this
      //触发getter,这里的作用只是为了触发gettre,因此不需要保存内容
      key.split('.').reduce((acc,curr) => {
        return acc[curr]
      },vm.$data)
      Dependency.temp = null   //为了防止订阅者数组被多次添加到数组中
    }
   
    update() {
      const value = this.key.split('.').reduce((acc,curr) => {
        return acc[curr]
      },vm.$data)
      this.callback(value)
    }
  }

部分拆分

// complie
class Complie{
    construct(el, vm){
        this.$vm = vm;
        this.$el = document.querySelect(el);
        if(this.$el){
            this.complie(this.$el)
        }
    }
    complie(el){
        const childNodes = el.childNodes;
        Array.from(childNodes).forEach((node)=>{
            if(this.isElement(node)){
                console.log('编译元素' + node.nodeName);
            }else if(this.isInterpolation(node)){
                console.log("编译插值文件" + node.textContent)
            }
            if(node.childNodes && node.childNodes.length>0){
                this.complie(node)
            }
        })
    }
    isElement(node){
        return node.nodeType == 1

    }
    isInterpolation(node){
        return node.nodeType == 3 && /\{\{(.*)\}\}\/.test(node.textContent) 
    }

}

// watch
class Watcher {
    constructor(vm, key, update){
        this.vm = vm
        this.key = key
        this.updaterFn = updater
        Dep.target = this
        this.vm[this.key]
        Dep.target = null
    }
    update(){
        this.updaterFn.call(this.vm, this.vm[this.key])
    }
}

class Dep{
    constructor(){
        this.deps = [];
    }
    addDep(dep){
        this.deps.push(dep)
    }
    notify(){
        this.deps.forEach((dep)=>dep.update())
    }
}

function defineReactive(obj, key, val){
    this.observe(val);
    const dep = new Dep();
    Object.defineProperty(obj, key , {
        get(){
            Dep.target && dep.addDep(Dep.target)
            return val
        },
        set(newVal){
            if(newVal === val) return
            dep.notify()
        }

    })
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勒布朗-前端

请多多支持,留点爱心早餐

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值