JavaScript Publish/Subscribe实现

发布订阅模式,一对多的关系,通过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:'发布的消息'
});

转载于:https://my.oschina.net/applepeel/blog/1510311

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值