MVVM框架的實(shí)現(xiàn)

最近總被問到vue雙向綁定的原理,所以整理實(shí)現(xiàn)一下

MVVM框架

  • M:Model,模型層
  • V:View,視圖層
  • VM:ViewModel,視圖模型,VM連接的橋梁

M層修改時(shí),VM層會(huì)監(jiān)測(cè)到變化,并通知V層修改;V層修改則會(huì)通知M層數(shù)據(jù)進(jìn)行修改。

雙向數(shù)據(jù)綁定的方式

發(fā)布-訂閱者模式
通過pub、sub來實(shí)現(xiàn)數(shù)據(jù)和視圖的綁定,使用麻煩。
臟值檢查
通過定時(shí)器輪訓(xùn)檢測(cè)數(shù)據(jù)是否發(fā)生變化。angular.js用此方法。
數(shù)據(jù)劫持
通過Object.defineProperty()來劫持各個(gè)屬性的setter、getter。vue.js采用數(shù)據(jù)劫持 + 發(fā)布-訂閱者模式,在數(shù)據(jù)變動(dòng)時(shí)發(fā)布消息給訂閱者。

實(shí)現(xiàn)思路

  • Compile:模板解析器,對(duì)模板中的指令插值表達(dá)式進(jìn)行解析,賦予不同的操作
  • Observe:數(shù)據(jù)監(jiān)聽器,對(duì)數(shù)據(jù)對(duì)象的所有屬性進(jìn)行監(jiān)聽
  • Watcher:將Compile的解析結(jié)果,與Observe的觀察對(duì)象連接起來

Compile

對(duì)模板中的指令和插值表達(dá)式進(jìn)行解析,并賦予不同的操作。

  • document.createDocumentFragment()
  • [].slice.call(likeArr)
    將偽數(shù)組轉(zhuǎn)換為數(shù)組的方法。具體參考這里
  • getVMValue方法主要為了解決復(fù)雜數(shù)據(jù)類型帶來的問題
  • 代碼
    compile.js
// 負(fù)責(zé)解析模板內(nèi)容
class Compile {
  constructor(el, vm) {
    this.el = typeof el === 'string' ? document.querySelector(el) : el
    this.vm = vm
    // 編譯模板
    if (this.el) {
      // 1.把子節(jié)點(diǎn)存入內(nèi)存 -- fragment
      let fragment = this.node2fragment(this.el)
      // 2.在內(nèi)存中編譯fragment
      this.compile(fragment)
      // 3.把fragment一次性添加到頁面
      this.el.appendChild(fragment)
    }
  }
  // 核心方法
  node2fragment(node) { // 把el中的子節(jié)點(diǎn)添加到文檔碎片中
    let fragment = document.createDocumentFragment()
    let childNodes = node.childNodes
    this.toArray(childNodes).forEach(element => {
      fragment.appendChild(element)
    });
    return fragment
  }
  compile(fragment) { // 編譯文檔碎片
    let childNodes = fragment.childNodes
    this.toArray(childNodes).forEach(node => {
      // 元素節(jié)點(diǎn) - 解析指令
      if (this.isElementNode(node)) {
        this.compileElement(node)
      }
      // 文本節(jié)點(diǎn) - 解析插值表達(dá)式
      if (this.isTextNode(node)) {
        this.compileText(node)
      }
      // 若還有子節(jié)點(diǎn),遞歸解析
      if (node.childNodes && node.childNodes.length > 0) {
        this.compile(node)
      }
    })

  }
  compileElement(node) {
    // 獲取當(dāng)前節(jié)點(diǎn)所有屬性
    let attr = node.attributes
    this.toArray(attr).forEach(attr => {
      // 解析vue指令
      let attrName = attr.name
      if (this.isDirective(attrName)) {
        let type = attrName.slice(2)
        let attrVal = attr.value
        if (this.isEventDirective(type)) {
          CompileUtil["eventHandler"](node, this.vm, type, attrVal)
        } else {
          CompileUtil[type] && CompileUtil[type](node, this.vm, attrVal)
        }
      }
    })
  }
  compileText(node) {
    CompileUtil.mustache(node, this.vm)
  }
  // 工具方法
  toArray(likeArr) { // 把偽數(shù)組轉(zhuǎn)換成數(shù)組
    return [].slice.call(likeArr)
  }
  isElementNode(node) { // 判斷元素節(jié)點(diǎn)
    return node.nodeType === 1
  }
  isTextNode(node) { // 判斷文本節(jié)點(diǎn)
    return node.nodeType === 3
  }
  isDirective(attrName) { // 判斷指令
    return attrName.startsWith('v-')
  }
  isEventDirective(attrName) { // 判斷事件
    return attrName.split(":")[0] === "on"
  }
}
let CompileUtil = {
  mustache(node, vm) {
    let txt = node.textContent
    let reg = /\{\{(.+)\}\}/
    if (reg.test(txt)){
      let expr = RegExp.$1
      node.textContent = txt.replace(reg, CompileUtil.getVMValue(vm, expr))      
    }
  },
  text(node, vm, attrVal) {
    node.textContent = this.getVMValue(vm, attrVal)
  },
  html(node, vm, attrVal) {
    node.innerHTML = this.getVMValue(vm, attrVal)
  },
  model(node, vm, attrVal) {
    node.value = this.getVMValue(vm, attrVal)
  },
  eventHandler(node, vm, type, attrVal) {
    let eventType = type.split(":")[1]
    let fn = vm.$methods[attrVal]
    if (eventType && fn) {
      node.addEventListener(eventType, fn.bind(vm))
    }
  },
  // 獲取VM中的數(shù)據(jù)
  getVMValue(vm, expr) {
    let data = vm.$data
    expr.split(".").forEach(key => {
      data = data[key]
    });
    return data
  }
}

vue.js

class Vue {
  constructor(options = {}) {
    // 給vue增加實(shí)例屬性
    this.$el = options.el
    this.$data = options.data
    this.$methods = options.methods

    if (this.$el) {
      new Compile(this.$el, this)
    }
  }
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <p>復(fù)雜數(shù)據(jù)</p>
    <p>{{car.color}}</p>
    <div v-text="car.brand"></div>
    <p>簡(jiǎn)單數(shù)據(jù)</p>
    <p>大家好,{{text}}</p>
    <p>{{msg}}</p>
    <div v-text="msg" title="hhhh"></div>
    <div v-html="msg" title="aaaa"></div>
    <input type="text" v-model="msg">
    <button v-on:click="clickFn">點(diǎn)擊</button>
  </div>
  <script src="./src/compile.js"></script>
  <script src="./src/vue.js"></script>
  <script>
    const vm = new Vue({
      el: '#app',
      data: {
        msg: 'hello world',
        text: 'hello text',
        car: {
          color: 'red',
          brand: 'polo'
        }
      },
      methods: {
        clickFn () {
          console.log(this.$data.msg)
        }
      }
    })
    console.log(vm)
  </script>
</body>
</html>

observe

數(shù)據(jù)劫持主要使用了object.defineProperty(obj, prop, descriptor)MDN鏈接

結(jié)合下面的小案例,來綜合說明過程

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    let obj = {
      name: 'fxd'
    }
    let temp = obj.name
    Object.defineProperty(obj, 'name', {
      configurable: true, // 屬性可配置
      enumerable: true, // 屬性可遍歷
      get () {
        // 每次獲取屬性時(shí),會(huì)被此方法劫持到
        console.log('獲取屬性')
        return temp
      },
      set (newValue) {
        console.log('改變屬性')
        temp = newValue
      }
    })
  </script>
</body>
</html>

執(zhí)行結(jié)果如下


在vue的源碼中,大概實(shí)現(xiàn)思路如下

  1. 新建observe.js
/* 
  observe給data中的所有數(shù)據(jù)添加getter和setter
  在獲取或設(shè)置data數(shù)據(jù)時(shí),方便實(shí)現(xiàn)邏輯
*/

class Observe {
  constructor(data) {
    this.data = data
    this.walk(data)
  }

  // 核心方法
  walk (data) { // 遍歷數(shù)據(jù),添加上getter和setter
    if (!data || typeof data !== "object") {
      return
    }
    Object.keys(data).forEach(key => {
      // 給key設(shè)置getter和setter
      this.defineReactive(data, key, data[key])
      // 如果data是復(fù)雜類型,遞歸walk
      this.walk(data[key])
    })
  }
  // 數(shù)據(jù)劫持
  defineReactive(obj, key, value) {
    let that = this
    Object.defineProperty(obj, key, {
      configurable: true,
      enumerable: true,
      get () {
        console.log('獲取',value)
        return value
      },
      set (newValue) {
        if (value === newValue) {
          return
        }
        console.log('設(shè)置', newValue)
        value = newValue
        // 如果value是對(duì)象
        that.walk(newValue)
      }
    })
  }
}
  1. index.html中引入observe.js
<script src="./src/observe.js"></script>
  1. vue.js中添加
    // 監(jiān)視data中的數(shù)據(jù)
    new Observe(this.$data)

Watcher

  • updatewatcher.js中對(duì)外暴露的更新頁面的方法,在observe.jsset中調(diào)用。因?yàn)?code>set劫持的是數(shù)據(jù)改變,這樣當(dāng)數(shù)據(jù)改變時(shí),就會(huì)調(diào)用update實(shí)現(xiàn)頁面更新
  • compile.js的指令/插值表達(dá)式處理的部分,newWatcher,用來將Watcher中新值填入對(duì)應(yīng)的指令/插值表達(dá)式中

上述方法的缺點(diǎn):不同的指令/插值表達(dá)式各自new了不同Watcher,這樣在在observe.jsset中不確定要調(diào)用哪一個(gè)Watcherupdate方法
解決方法:發(fā)布-訂閱者模式

發(fā)布-訂閱者模式
訂閱者:只需要訂閱
發(fā)布者:狀態(tài)改變時(shí),通知并自動(dòng)更新給所有的訂閱者
優(yōu)點(diǎn):解耦合


基本思路如下:

  • watch.js中設(shè)置Dep對(duì)象,用來管理、添加、通知訂閱者;將Watcher中的this存儲(chǔ)到Dep.target
  • observe.js的數(shù)據(jù)劫持中newDep,判斷并調(diào)用添加和通知訂閱者的方法

最后,優(yōu)化下復(fù)雜數(shù)據(jù)的更新,model指令中input雙向綁定,以及把datamethods中的數(shù)據(jù)掛載到vm實(shí)例上即可

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <p>復(fù)雜數(shù)據(jù)</p>
    <p>{{car.color}}</p>
    <div v-text="car.brand"></div>
    <p>簡(jiǎn)單數(shù)據(jù)</p>
    <p>大家好,{{text}}</p>
    <p>{{msg}}</p>
    <div v-text="msg" title="hhhh"></div>
    <div v-html="msg" title="aaaa"></div>
    <input type="text" v-model="msg">
    <button v-on:click="clickFn">點(diǎn)擊</button>
  </div>
  <script src="./src/watcher.js"></script>
  <script src="./src/observe.js"></script>
  <script src="./src/compile.js"></script>
  <script src="./src/vue.js"></script>
  <script>
    const vm = new Vue({
      el: '#app',
      data: {
        msg: 'hello world',
        text: 'hello text',
        car: {
          color: 'red',
          brand: 'polo'
        }
      },
      methods: {
        clickFn () {
          // this.$data.msg = '2222'
          this.msg = '2222222'
        }
      }
    })
    console.log(vm)
  </script>
</body>
</html>

observe.js

/* 
  observe給data中的所有數(shù)據(jù)添加getter和setter
  在獲取或設(shè)置data數(shù)據(jù)時(shí),方便實(shí)現(xiàn)邏輯
*/

class Observe {
  constructor(data) {
    this.data = data
    this.walk(data)
  }

  // 核心方法
  walk (data) { // 遍歷數(shù)據(jù),添加上getter和setter
    if (!data || typeof data !== "object") {
      return
    }
    Object.keys(data).forEach(key => {
      // 給key設(shè)置getter和setter
      this.defineReactive(data, key, data[key])
      // 如果data是復(fù)雜類型,遞歸walk
      this.walk(data[key])
    })
  }
  // 數(shù)據(jù)劫持
  // data中的每一個(gè)數(shù)據(jù)都維護(hù)一個(gè)dep對(duì)象,保存了所有訂閱了該數(shù)據(jù)的訂閱者
  defineReactive(obj, key, value) {
    let that = this
    let dep = new Dep()
    Object.defineProperty(obj, key, {
      configurable: true,
      enumerable: true,
      get () {
        // 如果Dep.target中有watcher,存儲(chǔ)到訂閱者數(shù)組中
        Dep.target && dep.addSub(Dep.target)
        return value
      },
      set (newValue) {
        if (value === newValue) {
          return
        }
        value = newValue
        // 如果value是對(duì)象
        that.walk(newValue)
        // 發(fā)布通知,讓所有的訂閱者更新內(nèi)容
        dep.notify()
      }
    })
  }
}

watch.js

/* 
  watcher負(fù)責(zé)將compile和observe關(guān)聯(lián)起來
*/
class Watcher {
  // 參數(shù)分別是:當(dāng)前實(shí)例,data中的名字,數(shù)據(jù)改變時(shí)的回調(diào)函數(shù)
  constructor(vm, expr, cb) {
    this.vm = vm
    this.expr = expr
    this.cb = cb

    // 將this存儲(chǔ)到Dep.target上
    Dep.target = this

    // 將expr的舊值存儲(chǔ)
    this.oldVal = this.getVMValue(vm, expr)

    // 清空Dep.target
    Dep.target = null
  }
  // 對(duì)外暴露更新頁面的方法
  update () {
    let oldVal = this.oldVal
    let newVal = this.getVMValue(this.vm, this.expr)
    if (oldVal != newVal) {
      this.cb(newVal, oldVal)
    }
  }
  // 獲取VM中的數(shù)據(jù)
  getVMValue(vm, expr) {
    let data = vm.$data
    expr.split(".").forEach(key => {
      data = data[key]
    });
    return data
  }
}
// dep對(duì)象 - 管理訂閱者,通知訂閱者
class Dep {
  constructor () {
    // 管理訂閱者
    this.subs = []
  }
  // 添加訂閱者
  addSub (watcher) {
    this.subs.push(watcher)
  }
  // 通知訂閱者
  notify () {
    // 遍歷所有訂閱者,調(diào)用watcher的update方法
    this.subs.forEach(sub => {
      sub.update()
    })
  }
}

compile.js

// 負(fù)責(zé)解析模板內(nèi)容
class Compile {
  constructor(el, vm) {
    this.el = typeof el === 'string' ? document.querySelector(el) : el
    this.vm = vm
    // 編譯模板
    if (this.el) {
      // 1.把子節(jié)點(diǎn)存入內(nèi)存 -- fragment
      let fragment = this.node2fragment(this.el)
      // 2.在內(nèi)存中編譯fragment
      this.compile(fragment)
      // 3.把fragment一次性添加到頁面
      this.el.appendChild(fragment)
    }
  }
  // 核心方法
  node2fragment(node) { // 把el中的子節(jié)點(diǎn)添加到文檔碎片中
    let fragment = document.createDocumentFragment()
    let childNodes = node.childNodes
    this.toArray(childNodes).forEach(element => {
      fragment.appendChild(element)
    });
    return fragment
  }
  compile(fragment) { // 編譯文檔碎片
    let childNodes = fragment.childNodes
    this.toArray(childNodes).forEach(node => {
      // 元素節(jié)點(diǎn) - 解析指令
      if (this.isElementNode(node)) {
        this.compileElement(node)
      }
      // 文本節(jié)點(diǎn) - 解析插值表達(dá)式
      if (this.isTextNode(node)) {
        this.compileText(node)
      }
      // 若還有子節(jié)點(diǎn),遞歸解析
      if (node.childNodes && node.childNodes.length > 0) {
        this.compile(node)
      }
    })

  }
  compileElement(node) {
    // 獲取當(dāng)前節(jié)點(diǎn)所有屬性
    let attr = node.attributes
    this.toArray(attr).forEach(attr => {
      // 解析vue指令
      let attrName = attr.name
      if (this.isDirective(attrName)) {
        let type = attrName.slice(2)
        let attrVal = attr.value
        if (this.isEventDirective(type)) {
          CompileUtil["eventHandler"](node, this.vm, type, attrVal)
        } else {
          CompileUtil[type] && CompileUtil[type](node, this.vm, attrVal)
        }
      }
    })
  }
  compileText(node) {
    CompileUtil.mustache(node, this.vm)
  }
  // 工具方法
  toArray(likeArr) { // 把偽數(shù)組轉(zhuǎn)換成數(shù)組
    return [].slice.call(likeArr)
  }
  isElementNode(node) { // 判斷元素節(jié)點(diǎn)
    return node.nodeType === 1
  }
  isTextNode(node) { // 判斷文本節(jié)點(diǎn)
    return node.nodeType === 3
  }
  isDirective(attrName) { // 判斷指令
    return attrName.startsWith('v-')
  }
  isEventDirective(attrName) { // 判斷事件
    return attrName.split(":")[0] === "on"
  }
}
let CompileUtil = {
  mustache(node, vm) {
    let txt = node.textContent
    let reg = /\{\{(.+)\}\}/
    if (reg.test(txt)){
      let expr = RegExp.$1
      node.textContent = txt.replace(reg, CompileUtil.getVMValue(vm, expr))  
      new Watcher(vm, expr, newVal => {
        node.textContent = txt.replace(reg, newVal)
      })    
    }
  },
  text(node, vm, attrVal) {
    node.textContent = this.getVMValue(vm, attrVal)
    // 通過Watcher監(jiān)聽attrVal,一旦變化,執(zhí)行回調(diào)
    new Watcher(vm, attrVal, newVal => {
      node.textContent = newVal
    })
  },
  html(node, vm, attrVal) {
    node.innerHTML = this.getVMValue(vm, attrVal)
    new Watcher(vm, attrVal, newVal => {
      node.innerHTML = newVal
    })
  },
  model(node, vm, attrVal) {
    let that = this
    node.value = this.getVMValue(vm, attrVal)
    // 實(shí)現(xiàn)雙向的數(shù)據(jù)綁定
    node.addEventListener('input', function () {
      that.setVMValue(vm, attrVal, this.value)
    })
    new Watcher(vm, attrVal, newVal => {
      node.value = newVal
    })
  },
  eventHandler(node, vm, type, attrVal) {
    let eventType = type.split(":")[1]
    let fn = vm.$methods[attrVal]
    if (eventType && fn) {
      node.addEventListener(eventType, fn.bind(vm))
    }
  },
  // 獲取VM中的數(shù)據(jù)
  getVMValue(vm, expr) {
    let data = vm.$data
    expr.split(".").forEach(key => {
      data = data[key]
    });
    return data
  },
  setVMValue(vm, expr, value) {
    let data = vm.$data
    let arr = expr.split(".")
    arr.forEach((key, index) => {
      if (index < arr.length - 1) {
        data = data[key]
      } else {
        data[key] = value
      }
    })
  }
}

vue.js

class Vue {
  constructor(options = {}) {
    // 給vue增加實(shí)例屬性
    this.$el = options.el
    this.$data = options.data
    this.$methods = options.methods

    // 監(jiān)視data中的數(shù)據(jù)
    new Observe(this.$data)

    // 將data和methods中的數(shù)據(jù)代理到vm上
    this.proxy(this.$data)
    this.proxy(this.$methods)

    if (this.$el) {
      new Compile(this.$el, this)
    }
  }
  proxy (data) {
    Object.keys(data).forEach(key => {
      Object.defineProperty(this, key, {
        enumerable: true,
        configurable: true,
        get () {
          return data[key]
        }, 
        set (newVal) {
          if (data[key] == newVal) {
            return
          }
          data[key] = newVal
        }
      })
    })
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容