简单实现
var publish = {} // 发布者对象
publish.clientList = []; // 存放订阅者回调函数缓存列表
publish.listen = function (fn) {
this.clientList.push(fn);
}
publish.trigger = function () { // 发布消息
publish.clientList.map(item=> {
item.apply(this, arguments);
});
}
//=======================测试=============================
publish.listen(function (message) {
alert(message);
});
publish.trigger("这是一条消息"); // 这是一条消息
缺点:发布者发布消息无差别发送,没有订阅该消息的订阅者也会受到该消息
解决办法:增加标识key值,只订阅自己感兴趣的消息。
代码示例
var publish = {};
publish.clientList = {} // 缓存列表,存放订阅者的回调函数
publish.listen = function (key, fn) {
if (!this.clientList[key]) { // 如果还没有订阅过此类消息,给该类消息创建一个缓存列表
this.clientList[key] = [];
}
this.clientList[key].push(fn);
}
publish.trigger = function () {
var key = Array.prototype.shift.call(arguments); // 取出key值
var fns = this.clientList[key]; //取出订阅者回调函数
if (!fns || fns.lenght === 0) {
return false; //没有订阅,则不做任何操作
}
fns.map((item)=>{
item.apply(this,arguments);
})
}
// =======================测试======================
var obj = {
name: '小黑不黑',
age: 20
};
publish.listen('orderer', (obj)=> {
console.log(obj);
});
publish.trigger("orderer", obj);
网友评论