/* @flow */

import { queueWatcher } from './scheduler'
import Dep, { pushTarget, popTarget } from './dep' import {
warn,
remove,
isObject,
parsePath,
_Set as Set,
handleError
} from '../util/index' let uid = 0 /**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives. 一个 watcher编译成 一个表达式 和 依赖集合, 还能出发回调当 v-model的值改变
这也能用到wathcer api中, 如果 vm.$watch('abc', fn);
*/
export default class Watcher {
vm: Component;
expression: string;
cb: Function;
id: number;
deep: boolean;
user: boolean;
lazy: boolean;
sync: boolean;
dirty: boolean;
active: boolean;
deps: Array<Dep>;
newDeps: Array<Dep>;
depIds: Set;
newDepIds: Set;
getter: Function;
value: any; constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: Object
) {
//这个watcher所属的vm
this.vm = vm // 一个vm 有多个watchers , vm.$watch(a,fn1) vm.$watch(b,fn2) {{b.UpperCase()}} 等等
vm._watchers.push(this)
// options
if (options) {
//是否深度检测依赖
this.deep = !!options.deep
this.user = !!options.user
this.lazy = !!options.lazy
this.sync = !!options.sync
} else {
this.deep = this.user = this.lazy = this.sync = false
}
this.cb = cb
this.id = ++uid // uid for batching
this.active = true
this.dirty = this.lazy // for lazy watchers
this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()
this.expression = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: ''
// parse expression for getter
if (typeof expOrFn === 'function') {
//监控函数
this.getter = expOrFn
} else {
//监控表达式, 注意 这里也会返回一个路径的函数
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = function () {}
process.env.NODE_ENV !== 'production' && warn(
`Failed watching path: "${expOrFn}" ` +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
)
}
}
this.value = this.lazy
? undefined
: this.get()
} /**
* Evaluate the getter, and re-collect dependencies.
*/
get () {
//Dep.target = this
pushTarget(this)
let value
const vm = this.vm
if (this.user) {
try {
// 因为传入了 vm, 所以在methods中可以取得this.data.abc
// 比如 this.getter 是 fucntion(){ return this.price * this.nums; }; 因为执行这个函数, 也就会去获取 this.price 和 this.nums的值
// 就会分别触发这两个数据的get方法, 然后这个watcher就会加入这两个数据的dep, this.push(depq) this.push(dep2); 通过这一步就收集了这个函数的两个依赖
value = this.getter.call(vm, vm)
} catch (e) {
handleError(e, vm, `getter for watcher "${this.expression}"`)
}
} else {
value = this.getter.call(vm, vm)
}
// "touch" every property so they are all tracked as
// dependencies for deep watching
//“触摸”每一个属性,这样它们都被跟踪为 深度观察依赖
    if (this.deep) {
traverse(value)
}

popTarget()
this.cleanupDeps()
return value
} /**
* Add a dependency to this directive.
添加一个依赖到这个指令
*/
addDep (dep: Dep) {
const id = dep.id
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id)
this.newDeps.push(dep)
if (!this.depIds.has(id)) {
dep.addSub(this)
}
}
} /**
* Clean up for dependency collection.
*/
cleanupDeps () {
let i = this.deps.length
while (i--) {
const dep = this.deps[i]
if (!this.newDepIds.has(dep.id)) {
dep.removeSub(this)
}
}
let tmp = this.depIds
this.depIds = this.newDepIds
this.newDepIds = tmp
this.newDepIds.clear()
tmp = this.deps
this.deps = this.newDeps
this.newDeps = tmp
this.newDeps.length = 0
} /**
* Subscriber interface.
* Will be called when a dependency changes.
*/
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
} /**
* Scheduler job interface.
* Will be called by the scheduler.
*/
run () {
if (this.active) {
const value = this.get()
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
const oldValue = this.value
this.value = value
if (this.user) {
try {
this.cb.call(this.vm, value, oldValue)
} catch (e) {
handleError(e, this.vm, `callback for watcher "${this.expression}"`)
}
} else {
this.cb.call(this.vm, value, oldValue)
}
}
}
} /**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers. 计算一个watcher的值, 这个只会被 延迟watchers调用
*/
evaluate () {
this.value = this.get()
this.dirty = false
} /**
* Depend on all deps collected by this watcher.
通过这个watcher, 收集所有的依赖?
*/
depend () {
let i = this.deps.length
while (i--) {
this.deps[i].depend()
}
} /**
* Remove self from all dependencies' subscriber list. 从所有的依赖订阅清单中移除自己
*/
teardown () {
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed.
// 移除依赖是一个昂贵的操作, 所有如果这个vm已经销毁le, 我们就跳一跳
if (!this.vm._isBeingDestroyed) {
remove(this.vm._watchers, this)
}
let i = this.deps.length
while (i--) {
this.deps[i].removeSub(this)
}
this.active = false
}
}
} /**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency. 递归追踪一个对象去唤起所有的已经转换的getters,
这样在一个对象的所以嵌套的熟悉都被收集成为一个深层的依赖
*/ const seenObjects = new Set()
function traverse (val: any) {
seenObjects.clear()
_traverse(val, seenObjects)
} function _traverse (val: any, seen: Set) {
let i, keys
const isA = Array.isArray(val)
if ((!isA && !isObject(val)) || !Object.isExtensible(val)) {
return
}
if (val.__ob__) {
const depId = val.__ob__.dep.id
if (seen.has(depId)) {
return
}
seen.add(depId)
}
if (isA) {
i = val.length
while (i--) _traverse(val[i], seen)
} else {
//for in 都不用了, 加快速度
keys = Object.keys(val)
i = keys.length
while (i--) _traverse(val[keys[i]], seen)
}
}

vue.js 源代码学习笔记 ----- $watcher的更多相关文章

  1. 从零开始学习Vue.js,学习笔记

    一.为什么学习vue.js methods 只有纯粹的数据逻辑,而不是去处理 DOM 事件细节. vue.js兼具angular.js和react的优点,并且剔除了他们的缺点 官网:http://cn ...

  2. vue.js路由学习笔记

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  3. 两万字Vue.js基础学习笔记

    Vue.js学习笔记 目录 Vue.js学习笔记 ES6语法 1.不一样的变量声明:const和let 2.模板字符串 3.箭头函数(Arrow Functions) 4. 函数的参数默认值 5.Sp ...

  4. vue.js 源代码学习笔记 ----- html-parse.js

    /** * Not type-checking this file because it's mostly vendor code. */ /*! * HTML Parser By John Resi ...

  5. vue.js 源代码学习笔记 ----- instance state

    /* @flow */ import Dep from '../observer/dep' import Watcher from '../observer/watcher' import { set ...

  6. vue.js 源代码学习笔记 ----- core lifecycle

    /* @flow */ import config from '../config' import Watcher from '../observer/watcher' import { mark, ...

  7. vue.js 源代码学习笔记 ----- 工具方法 lang

    /* @flow */ // Object.freeze 使得这个对象不能增加属性, 修改属性, 这样就保证了这个对象在任何时候都是空的 export const emptyObject = Obje ...

  8. vue.js 源代码学习笔记 ----- 工具方法 env

    /* @flow */ /* globals MutationObserver */ import { noop } from 'shared/util' // can we use __proto_ ...

  9. vue.js 源代码学习笔记 ----- observe

    参考 vue 2.2.6版本 /* @flow */ //引入订阅者模式 import Dep from './dep' import { arrayMethods } from './array' ...

随机推荐

  1. 同时执行2条不同sql

    select * from  a: select *from b; 用分号结束.

  2. jquery试题

    1.下面哪种说法是正确的? 您的回答:jQuery 是 JavaScript 库 2.jQuery 使用 CSS 选择器来选取元素? 您的回答:正确 3.jQuery 的简写是? 您的回答:$ 符号 ...

  3. CSS 布局 - 水平 & 垂直对齐

    CSS 布局 - 水平 & 垂直对齐 一.元素居中对齐 要水平居中对齐一个元素(如 <div>), 可以使用 margin: auto;. 设置到元素的宽度将防止它溢出到容器的边缘 ...

  4. 尝试编辑java程序

    尝试编译java程序 之前在用软件eclipse编译过简单的hello  java程序,因为软件操作简单,后来学会了用命令符来编译程序.代码如下 public class abc     {      ...

  5. C++开学第二次作业(5.14)

    开学第二次作业(5.14) 代码传送门 题目 给定一个常数K以及一个单链表L,请编写程序将L中每K个结点反转.例如:给定L为1→2→3→4→5→6,K为3,则输出应该为3→2→1→6→5→4:如果K为 ...

  6. [转]C语言 gets()和scanf()函数的区别

    scanf( )函数和gets( )函数都可用于输入字符串,但在功能上有区别.若想从键盘上输入字符串"hi hello",则应该使用__gets__函数. gets可以接收空格:而 ...

  7. Python for循环文件

    for 循环遍历文件:打印文件的每一行 #!/usr/bin/env python fd = open('/tmp/hello.txt') for line in fd: print line, 注意 ...

  8. mvn设置

    mvn仓库网址: https://mvnrepository.com 安装好maven后,一定要确认安装路径下的setting.xml与本地仓库中的setting.xml一致. 坐标: 什么是坐标? ...

  9. java quartz

     什么是Quartz Quartz是一个完全由Java编写的开源作业调度框架,为在Java应用程序中进行作业调度提供了简单却强大的机制.Quartz允许开发人员根据时间间隔来调度作业.它实现了作业和触 ...

  10. Covariance and Contravariance (C#)

    Covariance and Contravariance (C#) https://docs.microsoft.com/en-us/dotnet/articles/csharp/programmi ...