前端JS的服务订阅&服务发布

var eventCenter =
{
	sub:function(mesName, mesCallback){
	    this.argus=this.argus||{};
	    this.argus[mesName]=this.argus[mesName]||[];
	    this.argus[mesName].push(mesCallback);
	},
	pub:function(){
	    var args=Array.prototype.slice.call(arguments,0);
	    var mesName=args.shift();
	    if(!this.argus || !this.argus[mesName]){
	        return this;
	    }
	    for(var i=0;i<this.argus[mesName].length;i++){
	        this.argus[mesName][i].apply(this,args)
	    }
	}
}

//js事件订阅
eventCenter.sub('a',function(){
     console.log(2);
});

eventCenter.sub('remote',function(){
     console.log('remote call');
});

eventCenter.sub('timeout',function(){
     setTimeout(function() {
	 eventCenter.pub('remote');
     }, 5000);
})

//js事件发布
eventCenter.pub('a');
eventCenter.pub('timeout');
posted @ 2018-07-20 09:28  心无引擎,眼无流派  阅读(213)  评论(0编辑  收藏  举报