美文网首页
vue源码分析(七)核心函数之Dep

vue源码分析(七)核心函数之Dep

作者: vue爱好者 | 来源:发表于2020-04-21 20:49 被阅读0次

我们先打开文件src/core/observer/dep.js
代码如下:

/**
 * 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)
  }
  //  如果`target`存在就会继续添加监听
  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() // 执行更新
    }
  }
}

可以看到有如下几个方法:
constructor 构造函数
addSub 添加监听
removeSub 删除监听
depend 如果target存在就会继续添加监听
notify 通知监听者

相关文章

网友评论

      本文标题:vue源码分析(七)核心函数之Dep

      本文链接:https://www.haomeiwen.com/subject/zjekyhtx.html