一、观察者模式的概念
观察者模式(又叫发布-订阅模式),它定义对象间的一种一对多的依赖关系,当一个对象的状 态发生改变时,所有依赖于它的对象都将得到通知。
出自《JavaScript设计模式与开发实践》的官方定义。
二、结合应用场景深入理解
不论是在程序世界里还是现实生活中,观察者模式(发布-订阅模式)的应用都非常之广泛。
2.1 现实生活中的观察者模式
我们先看一个现实中的例子,售楼买房的案例。售楼处是发布者,买房者是订阅者,监听订阅楼房售卖的消息,中间需要一个记录楼房情况的花名册。理清楚思绪后,我们可以用JavaScript来实现,具体代码如下:
// 发布-订阅功能
var event = {
clientList: [],
listen: function(key, fn){
if(!this.clientList[key]){
this.clientList[key] = [];
}
this.clientList[key].push(fn);// 订阅的消息添加进缓存列表
},
trigger: function(){
var key = Array.prototype.shift.call(arguments),
fns = this.clientList[key];
if(!fns || !fns.length) {
return false;
}
for(var i = 0, fn;fn = fns[i++];) {
fn.apply(this, arguments);
}
},
remove: function(key, fn){// 取消订阅
var fns = this.clientList[key];
if(!fns) return false;// 如果key对应的消息没有被订阅,则直接返回
if(!fn){// 如果没有传入具体的回调函数,表示需要取消 key 对应消息的所有订阅
fns && (fns.length = 0)
}else{
for(var l = fns.length-1;l>=0;l--){// 反向遍历订阅的回调函数列表
var _fn = fns[l];
if(_fn === fn){
fns.splice(l,1);// 删除订阅者的回调函数
}
}
}
}
}
// 给订阅对象,安装发布-订阅功能
var installEvent = function(obj){
for(var i in event) {
obj[i] = event[i];
}
}
复制代码
以上,我们就完成了基本发布订阅模式的设计与实现,其中event
对象中定义消息缓存队列 clientList
、监听订阅函数 listen
、发布函数 trigger
、取消订阅函数remove
。
2.2 Vue双向绑定的实现原理
Vue双向绑定原理(又称响应式原理)是高频的面试题,其内部实现也属于观察者模式。今天我们就来剖析看看吧,先来看张官网介绍响应式原理的流程图:
从上图,我们不难看出Vue双向绑定实现逻辑里有有三个关键角色:
- observer(监听器):在Vue数据双向绑定的角色结构里,所谓的 observer 不仅是一个数据监听器,它还需要对监听到的数据进行转发——也就是说它同时还是一个发布者。
- watcher(订阅者):observer 把数据转发给了真正的订阅者——watcher对象。Watcher订阅者就是Observe和Compile之间的通信桥梁,主要做的事情是:
a、在自身实例化时往属性订阅器(dep)里面添加自;
b、自身必须有一个update()方法;
c、待属性变动dep.notice()通知时,能调用自身的update()方法,并触发Compile中绑定的回调,然后功成身退。 - compile(编译器):MVVM 框架特有的角色,负责对每个节点元素指令进行扫描和解析,指令的数据初始化、订阅者的创建这些“杂活”也归它管~
源码中可以找到具体的实现:
Observer: src/core/observer/index.js
export class Observer {
value: any;
dep: Dep;
vmCount: number; // number of vms that have this object as root $data
constructor (value: any) {
this.value = value
this.dep = new Dep()
...
this.walk(value)
}
// 遍历obj的属性,执行defineReactive
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i])
}
}
...
}
export function defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
const dep = new Dep()
const property = Object.getOwnPropertyDescriptor(obj, key)
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
const getter = property && property.get
const setter = property && property.set
if ((!getter || setter) && arguments.length === 2) {
val = obj[key]
}
let childOb = !shallow && observe(val)
// 为当前属性安装监听器
Object.defineProperty(obj, key, {
// 可枚举
enumerable: true,
// 不可配置
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
...
// #7981: for accessor properties without setter
if (getter && !setter) return
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify()
}
})
}
复制代码
Watcher: src/core/observer/watcher.js
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: SimpleSet;
newDepIds: SimpleSet;
before: ?Function;
getter: Function;
value: any;
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
this.vm = vm
if (isRenderWatcher) {
vm._watcher = this
}
vm._watchers.push(this)
// options
if (options) {
this.deep = !!options.deep
this.user = !!options.user
this.lazy = !!options.lazy
this.sync = !!options.sync
this.before = options.before
} 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 = noop
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 () {
pushTarget(this)
let value
const vm = this.vm
try {
value = this.getter.call(vm, vm)
} catch (e) {
if (this.user) {
handleError(e, vm, `getter for watcher "${this.expression}"`)
} else {
throw e
}
} finally {
// "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)
}
}
}
}
/**
* Depend on all deps collected by this watcher.
*/
depend () {
let i = this.deps.length
while (i--) {
this.deps[i].depend()
}
}
...
}
复制代码
Compiler: src/compiler/index.js
export const createCompiler = createCompilerCreator(function baseCompile (
template: string,
options: CompilerOptions
): CompiledResult {
// 1. parse 解析成 AST 抽象语法树
const ast = parse(template.trim(), options)
if (options.optimize !== false) {
// 2. optimize 优化
optimize(ast, options)
}
// 3. generate 代码生成
const code = generate(ast, options)
return {
ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
})
复制代码
三、总结
观察者模式是JavaScript设计模式最为重要的模式,也是面试的高频考题。通过结合上述案例分析,相信大家可以充分理解观察者这一设计模式。
本文正在参与「掘金小册免费学啦!」活动, 点击查看活动详情
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END