/* @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. jQuery height() 需要注意的地方

    var aNode = $('#id'); var height = aNode.height(); //如果在获取height前,aNode已经是display:none 或者说 aNode是隐藏的 ...

  2. Jquery2 基础核心

    学习要点: 1.代码风格 2.加载模式 3.对象互换 4.多个库之间的冲突 本节简单的介绍一下jQuery 一些核心的问题. 一.代码风格 在jQuery程序中,不管是页面元素的选择.内置的功能函数, ...

  3. Linux下安装SVN服务端

    安装 使用yum安装非常简单: yum install subversion 配置 2.1. 创建仓库 我们这里在/home下建立一个名为svn的仓库(repository),以后所有代码都放在这个下 ...

  4. Java GC垃圾回收

    Java的内存分配和回收也主要在Java的堆上进行的,Java的堆中存储了大量的对象实例,所以Java的堆也叫GC堆. Java在垃圾收集的过程中,主要用到了分代收集算法,具体有复制.标记清除.标记压 ...

  5. 初入spring boot(八 )Spring Data REST

    1. 什么是Spring Data REST Spring Data JPA是基于Spring Data 的Repository之上,可以将Repository自动输出为REST资源.目前Spring ...

  6. gdb 调试coredump文件过程:

    第一步:首先需要一个进程的coredump文件,怎么搞出coredump文件呢? 1. ps -fax|grep                 进程名称 找到进程的pid 2.gdb -p pid ...

  7. Memcached flush_all 命令

    Memcached flush_all 命令用于用于清理缓存中的所有 key=>value(键=>值) 对. 该命令提供了一个可选参数 time,用于在制定的时间后执行清理缓存操作. 语法 ...

  8. 基于cornerstone.js的cornerstoneWADOImageLoader

    上一篇简单介绍了cornerstone.js的相关使用介绍和基于cornerstone的web库cornerstoneWADOImageLoader,在实际开发中遇到了相关的一些问题,在这里说明一下, ...

  9. vue-router之学习笔记

    用 Vue.js + vue-router 创建单页应用,是非常简单的.使用 Vue.js ,我们已经可以通过组合组件来组成应用程序,当你要把 vue-router 添加进来,我们需要做的是,将组件( ...

  10. thinkphp3.2笔记(1)目录,控制器及url模式,地址解析

    一.目录 Application  :  tp默认的应用代码存储的目录 Public :     Tp 默认的存储静态资源的目录,img,css,js ThinkPHP  :   Tp  框架的源代码 ...