varEventBus={topics:{},subscribe:function(topic,listener){// create the topic if not yet createdif(!this.topics[topic])this.topics[topic]=[];// add the listenerthis.topics[topic].push(listener);},publish:function(topic,data){// return if the topic doesn't exist, or there are no listenersif(!this.topics[topic]||this.topics[topic].length<1)return;// send the event to all listenersthis.topics[topic].forEach(function(listener){listener(data||{});});}};EventBus.subscribe('foo',alert);EventBus.publish('foo','Hello World!');
(function(){vareventService=this.EventService={};var_listeners={};eventService.add=function(topic,func){if(!funcinstanceofFunction){console.warn(topic+" must add a function.");}if(!_listeners[topic]){_listeners[topic]=[];}_listeners[topic].push(func)};eventService.remove=function(topic,func){if(_listeners[topic]){varindex=_listeners[topic].indexOf(func);if(index!==-1){_listeners[topic].splice(index,1);}}};eventService.fire=function(topic,data){varlisteners;if(typeoftopic!=='string'){console.warn('EventDispatcher','First params must be an event type (String)')}elseif(_listeners[topic]==undefined)console.warn('EventDispatcher','No Event Register');else{_listeners[topic].forEach(function(func){func(data);});}};returneventService;}.call(this));