Created
August 1, 2014 21:04
-
-
Save bigeyex/0394b61cc443ac291173 to your computer and use it in GitHub Desktop.
broadcast and receive global events in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
hi, how can i unsubscribe ?