實現(xiàn) MVVM 類 Vue 迷你框架(四)
如何實現(xiàn) MVVM 類 Vue 迷你框架(四)
接下來我們需要做什么處理呢?
數(shù)據(jù) getter 的時候?qū)?shù)據(jù)添加 watcher 監(jiān)聽 數(shù)據(jù) setter 的時候,通知 watcher 更新
那么我們需要一個 Dep 類:
需要一個用于添加 watcher 實例 需要一個用于通知 watcher 實例更新
class Dep {
constructor() {
this.deps = []
}
addDep(watcher) {
this.deps.push(watcher);
}
notify() {
this.deps.forEach(watcher => watcher.update());
}
}
所以我們還需要一個 watcher 類
這個類就是用來更新數(shù)據(jù)的
class Watcher {
constructor(vm, key, updater) {
// 需要更新到那個 vm 對象上
// 對應是那個 key
this.$vm = vm
this.$key = key
this.$updater = updater
Dep.target = this // 將當前實例指定到 Dep 的靜態(tài)屬性上
vm[key]; // 初始化讀取一下出發(fā) getter
Dep.target = null // 置空
}
// 未來用于更新 DOM 的函數(shù), 由 Dep 通知調(diào)用
update() {
this.$updater.call(this.$vm, this.$vm[this.$key]);
}
}
那么我們在哪里使用這個依賴收集,以及觸發(fā)數(shù)據(jù)更新呢
在響應式處理,get 數(shù)據(jù)的時候,對其進行依賴收集 在響應式處理,set 數(shù)據(jù)的時候,對其進行數(shù)據(jù)更新
function defineReactive(obj, key, val) {
// 初始化響應式數(shù)據(jù)
observe(val);
const dep = new Dep(); // 每個 key 對應創(chuàng)建一個 Dep 實例
let curVal = val;
Oject.defineProperty(obj, key, {
get() {
// 建立 watcher 與 dep 的映射
Dep.target && dep.addDep(Dep.target);
return curVal
}
set(newVal) {
if(newVal !== curVal) {
observe(newVal); // 設(shè)置響應式
curVal = newVal; // 重新賦值
dep.notify(); // 通知更新
}
}
})
}
評論
圖片
表情
