发布订阅模式,一对多的关系,通过subscribe订阅相关信息,然后在callback中处理
publish发布信息,key与订阅的时候传递的保持一致,info为一个对象,callback中进行相应的处理。
export default class APLNotificationMgr{
static getInstance(){
if (null == APLNotificationMgr.sm_instance){
APLNotificationMgr.sm_instance = new APLNotificationMgr;
}
return APLNotificationMgr.sm_instance;
}
constructor(){
this._notifyItemList = new Array();
}
subscribe(key:String, callback:Function){
const item = new APLNotificationItem(key, callback);
this._notifyItemList.push(item);
return item;
}
publish(key:String, info:Object){
this._notifyItemList.forEach((item)=>{
this._executeAsync(key, info, item.notify.bind(item));
});
}
remove(item:APLNotificationItem){
let index = 0;
for (const itemTmp of this._notifyItemList){
if (itemTmp === item){
this._notifyItemList.splice(index, 1);
break;
}
index++;
}
}
removeAll(){
this._notifyItemList.splice(0, this._notifyItemList.length);
}
async _executeAsync(key:String, info:Map, callback:Function){
if (!!callback){
callback(key, info);
}
}
static sm_instance = null;
}
class APLNotificationItem{
constructor(key:String, notify:Function){
this._key = key;
this._notify = notify;
}
notify(key:String, info:Map){
if (this._key === key){
if (!!this._notify){
this._notify(info);
}
}
}
}
Eg:
订阅
componentWillMount(){
this._notifyList = new Array();
this._notifyList.push(APLNotificationMgr.getInstance().subscribe('mykey', (info)=>{
console.log(info);
}));
}
componentWillUnmount(){
this._notifyList.forEach((notifyItem)=>{
APLNotificationMgr.getInstance().remove(notifyItem);
});
}
发布
APLNotificationMgr.getInstance().publish('mykey' {
text:'发布的消息'
});