您的位置:首页 > Web前端 > Vue.js

vue.js 源代码学习笔记 ----- Dep

2017-06-22 14:34 836 查看
/* @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() }

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: