发布者订阅模式简介
发布—订阅模式又叫观察者模式,它定义对象间的一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都将得到通知。在javascript开发中,一般用事件模型来替代传统的发布—订阅模式。
代码实现如下
//定义发布者订阅模式模型
function message () {
this.messageList = {} //消息列表
}
/**
* 设置订阅者
* key 标识(string类型)
* fn 消息(函数类型)
*/
message.prototype.on = function (key, fn) {
if (!key || !fn) return;
if (!this.messageList[key]) this.messageList[key] = [] //如果没有订阅列表对其进行初始化
this.messageList[key].push(fn) //将对应的消息存到消息列表中
}
/**
* 发布消息
*/
message.prototype.emit = function () {
const key = Array.prototype.shift.call(arguments) //取出消息
const fns = this.messageList[key] //取出对应的消息列表
if(!fns || fns.length === 0 ) return console.log(false) //如果没有订阅该消息则返回
console.log('w')
for(let i = 0;i < fns.length;i++){
fns[i].apply(this,arguments) //其中arguments 是参数
}
}
/**
* 取消订阅者
* key 标识(string类型)
* fn 消息(函数类型)
*/
message.prototype.off = function(key,fn){
const fns = this.messageList[key]
//如果没有消息则返回
if(!fns){
return false
}
//如果没有传入具体回调函数,则删除所有订阅信息
//如果有则删除对应的订阅信息
if(!fn){
delete this.messageList[key]
}else{
let index = fns.indexOf(fn)
this.messageList[key].splice(index,1)
}
}