订阅-发布模式
发布—订阅模式又叫观察者模式「Observer Pattern」,它定义对象间的一种一对多的依赖关系,当一个对象的状 态发生改变时,所有依赖于它的对象都将得到通知。在 JavaScript 开发中,我们一般用事件模型 来替代传统的发布—订阅模式。
模式动机
实现
const salesOffices = {} // 定义售楼处
salesOffices.clientList = [] // 缓存列表,存放订阅者的回调函数
salesOffices.listen = function(fn) {
// 增加订阅者
this.clientList.push(fn) // 订阅的消息添加进缓存列表
}
salesOffices.trigger = function() {
// 发布消息
for (let i = 0, fn; (fn = this.clientList[i++]); ) {
fn.apply(this, arguments) // (2) //
}
}取消订阅
小结
Last updated
Was this helpful?