具体模式内容介绍网上能搜得到一堆堆..
下面就是贴出下自己倒腾的代码内容...
(function(global){
"use strice";
var Pubsub = function(){
var obj = {};//存储状态数据
//发布
this.publish = function(type , param){
//条件不存在直接抛错
if(!obj[type]){
console.error(`${type} is not define!!!!`);
return;
}
obj[type].forEach(value => {
value.func(type , param);
});
};
//订阅
this.subscribe = function(type){
obj[type] = obj[type] ? obj[type] : [];
obj[type].push({
func: showMsg,
});
};
var showMsg = function(type , param){
console.log(`订阅的内容是:${type} : 发布的数据是:${param}`);
};
};
global.pubsub = new Pubsub();
})(this);
pubsub.subscribe("test");
pubsub.publish("test" , "hello world");
pubsub.publish("demo" , "测试报错信息");