Skip to content

Commit

Permalink
基本的依赖收集
Browse files Browse the repository at this point in the history
  • Loading branch information
helloforrestworld committed Feb 18, 2020
1 parent 9c89ad5 commit 29a4f8d
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 1 deletion.
30 changes: 30 additions & 0 deletions source/vue/observe/dep.js
@@ -0,0 +1,30 @@
let id = 0
class Dep {
constructor() {
this.id = id++
this.subs = [] // 存放watcher订阅者
}

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

notify() {
this.subs.forEach(watcher => watcher.update())
}
}

// 保存当前watcher
// 后面使用
const stack = []
export function pushTarget(watcher) {
Dep.target = watcher
stack.push(watcher)
}

export function popTarget() {
stack.pop()
Dep.target = stack[stack.length - 1]
}

export default Dep
11 changes: 11 additions & 0 deletions source/vue/observe/observer.js
@@ -1,13 +1,21 @@
import { observe } from './index'
import { newArrayProto, observeArray } from './array'
import Dep from './dep'

export function defineReactive(data, key, value) {
// 如果value是对象的话,需要继续观察一层
observe(value)

// 给每个属性都添加一个dep
const dep = new Dep()

Object.defineProperty(data, key, {
get() {
console.log('获取数据')
// 取数据的时候进行依赖收集
if (Dep.target) {
dep.addSub(Dep.target)
}
return value
},
set(newValue) {
Expand All @@ -18,6 +26,9 @@ export function defineReactive(data, key, value) {

// defineReactive执行是一个闭包,value值会共享。
value = newValue

// 数据变化,通知更新视图
dep.notify()
}
})
}
Expand Down
14 changes: 13 additions & 1 deletion source/vue/observe/watcher.js
@@ -1,3 +1,5 @@
import { pushTarget, popTarget } from './dep'

let id = 0 // 每个watcher的标识
class Watcher {
/**
Expand All @@ -17,11 +19,21 @@ class Watcher {
this.opts = opts
this.id = id++

this.get() // 创建watcher时候默认会调用一次get方法
// 创建watcher时候默认会调用一次get方法
this.get()
}

get() {
// 往Dep添加一个target,指向当前watcher
pushTarget(this)
this.getter && this.getter()
// getter执行完毕后,把当前watcher从Dep.target中剔除
popTarget()
}

update() {
console.log('watcher update')
this.get()
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/index.js
Expand Up @@ -24,3 +24,5 @@ const vm = new Vue({
// console.log(vm.arr[3].a)
// console.log(vm.arr[0].a)
// vm.arr[0].a = 123

window.vm = vm

0 comments on commit 29a4f8d

Please sign in to comment.