/* @flow */ import type Watcher from './watcher' import { remove } from '../util/index' let uid = 0 /** * A dep is an observable that can have multiple * directives subscribing to it.
一個訂閱模式 可以有多個指令去訂閱他 */ export default class Dep { static target: ?Watcher; id: number; subs: Array<Watcher>; constructor () { this.id = uid++ this.subs = [] } addSub (sub: Watcher) { this.subs.push(sub) } removeSub (sub: Watcher) { remove(this.subs, sub) } depend () { if (Dep.target) { Dep.target.addDep(this) } } notify () { // stabilize the subscriber list first , 避免改動影響到原來的數組 const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) { subs[i].update() } } } // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time.
// 一個全局唯一的, 因為只能有一個watcher 依賴的對象的值 被計算, 在任何時間
Dep.target = null
/*
利用這個中間變量, 緩存已有的target, 在 pushTarget 函數, 使用傳入的target 代替 Dep.target; 然后使用 Dep.target
最后使用 popTarget 還原 ; 主要是為了Observe中的get方法, 判斷當前是否有watcher(Dep.target), 如果有就在dep增加這個屬性的依賴, Dep.target.depend( dep1 )
比如 methods 的每一個方法可以是 一個 watcher, 這個wactcher可能會依賴多個 data里面的屬性
*/
const targetStack = []
//放入 dep的 訂閱者 export function pushTarget (_target: Watcher) { if (Dep.target) targetStack.push(Dep.target) Dep.target = _target }
//得到一個 dep的 訂閱者
export function popTarget () { Dep.target = targetStack.pop() }