观察者模式
观察者模式是一种一对多的关系,他有两个主体,一个是被观察者dep,另一个是观察者watcher,这两者的关系如何解释呢。既然是观察,那么一定是要侦听数据的改变的,而我们的数据一般都是放在data里面,这里就是把data里面的数据通过递归存放在被观察者例表中,而需要用到这些数据的模板放在观察者列表中,与之对应。当被观察者需求变化时,就会通过notify去挨个通知观察者watcher。
发布订阅模式
发布订阅模式有三个主体,与观察者模式不同的是,他是由发布者-事件通道(调度中心)-订阅者,因为有事件通道的存在,所以发布者和订阅者二者是不知道彼此的,这样也降低了耦合性,他其实也是一种对象间一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于他的对象都将得到状态改变的通知。- 常见的发布订阅
vue 中的emit
redux 中的 subscribe
定义 on 和 emit
class Events {
// 订阅事件
$on = function() {}
// 发布
$emit = function() {}
}
const events = new Events()
events.$on('test', function() {})
events.$emit('test', 'hello')
Copied!
#实现 on 添加订阅
class Events {
clientlist = {}
// 订阅事件
$on = function(key, fn) {
if (!this.clientlist[key]) {
this.clientlist[key] = []
}
this.clientlist[key].push(fn)
}
// 发布
$emit = function() {}
}
const events = new Events()
events.$on('test', function(data) {
console.log(data, '----')
})
events.$on('test', function(data) {
console.log(data, '----')
})
Copied!
#实现 emit 发布
// 发布
$emit = function(key, val) {
Object.keys(this.clientlist).forEach(item => {
if (!this.clientlist[key]) {
return false
}
this.clientlist[key].forEach(fn => fn(val))
})
}