简介
观察者模式是一种一对多的关系设计方案,一旦有变化发生,所有的订阅者都会响应。
const Event = function() {
let clientList = {}
let listen = null
let trigger = null
let remove = null
listen = function(key, fn) {
const fns = clientList[key]
if(!fns) {
clientList[key] = []
}
clientList[key].push(fn)
}
trigger = function(key, message) {
const fns = clientList[key]
if(!fns) return false
for(let i = 0, len = fns.length; i < len; i++) {
const fn = fns[i]
fn(message)
}
}
remove = function(key, fn) {
const fns = clientList[key]
if(!fns) return false
if(!fn) {
clientList[key] = []
} else {
for(let i = 0, len = fns.length; i++) {
const _fn = fns[i]
if(_fn === fn) {
fns.splice(i, 1)
}
}
}
}
return {
listen: listen,
trigger: trigger,
remove: remove
}
}
Vue中的订阅者模式
订阅者 Dep
class Dep {
constructor(){
this.subs = []
}
addSub(sub) {
this.subs.push(sub)
}
notify() {
this.subs.forEach(sub => {
sub.update()
})
}
}
观察者Watcher
class Watcher {
constructor() {
Dep.target = this
}
update() {
}
}
依赖收集 Observer
function Observer(obj) {
Object.keys(obj).forEach(key => {
let val = obj[key]
const dep = new Dep()
Object.defineProperty(obj, key , {
enumerable: true,
configurable: true,
get: function reactiveGetter() {
dep.addSub(Dep.target) // 把watch对象存储到dep的subs中
return val
}
,
set: function(newVal) {
if(val === newVal) return
val = newVal
// 在set的时候触发更新
dep.notify()
}
})
}