Skip to content

Instantly share code, notes, and snippets.

@bigeyex
Created August 1, 2014 21:04
Show Gist options
  • Save bigeyex/0394b61cc443ac291173 to your computer and use it in GitHub Desktop.
Save bigeyex/0394b61cc443ac291173 to your computer and use it in GitHub Desktop.
broadcast and receive global events in javascript
/*
Dispatcher module
by: wangyu ([email protected])
dispatch global event
usage:
- fire an event:
dispatcher.dispatch('example.event.name', arg1, arg2...)
- subscribe an event:
dispatcher.subscribe('example.event.name', function(arg1, arg2...){});
*/
function Dispatcher(){
this.eventList = {};
var self = this;
this.subscribe = function(eventName, eventHandler){
if(self.eventList[eventName]===undefined){
self.eventList[eventName] = [];
}
self.eventList[eventName].push(eventHandler);
};
this.dispatch = function(eventName){
var args = Array.prototype.slice.call(arguments);
args.shift();
var eventList = self.eventList[eventName];
if(eventList!==undefined){
for(var i in eventList){
eventList[i].apply(this, args);
}
}
};
}
window.dispatcher = new Dispatcher();
@alilishan
Copy link

hi, how can i unsubscribe ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment