Dep源码

178 阅读1分钟

dep类极为简单,一个只有四个实例方法:

addSub:添加watcher

depend:添加依赖,本质也是添加watcher,和addSub不同的是会先判断一下是否有target

removeSub:删除watcher

notify:for循环批量执行每个watcher里面的update函数(一个dep可能管理多个watcher)

Dep.target = null

当前正在计算的watcher,必须全局唯一,因为同一时间只能有一个watcher在计算(why)

dep.js源码

/* @flow */

import type Watcher from './watcher'
import { remove } from '../util/index'
import config from '../config'

let uid = 0

/**
 * A dep is an observable that can have multiple
 * directives subscribing to it.
 */
// Dep作用主要是建立数据和watch之间的桥梁
export default class Dep {
  static target: ?Watcher;
  id: number;
  subsArray<Watcher>;

  constructor () {
    this.id = uid++
    this.subs = []
  }

  addSub (subWatcher) {
    this.subs.push(sub)
  }

  removeSub (subWatcher) {
    remove(this.subs, sub)
  }

  depend () {
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }

  notify () {
    // stabilize the subscriber list first
    const subs = this.subs.slice()
    if (process.env.NODE_ENV !== 'production' && !config.async) {
      // subs aren't sorted in scheduler if not running async
      // we need to sort them now to make sure they fire in correct
      // order
      subs.sort((a, b) => a.id - b.id)
    }
    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.
Dep.target = null
const targetStack = []

export function pushTarget (_target: ?Watcher) {
  if (Dep.target) targetStack.push(Dep.target)
  Dep.target = _target
}

export function popTarget () {
  Dep.target = targetStack.pop()
}