A simple JS event dispatcher that relies on a common key for the handler and data to dispatch actions.
var eventDispatcher = (function (eventDispatcher) {
var eventHandlers = {};
var eventDispatcher.register = function (key, handler) {
eventHandlers[key] = handler;
};
eventDispatcher.dispatch = function (data) {
for (var eventKey in eventHandlers) {
if (eventKey in data) {
eventHandlers[eventKey](data[eventKey]);
}
}
};
return eventDispatcher;
})(eventDispatcher || {});
// binding handlers to events
eventDispatcher.register('foo', function (data) {
alert(data);
});
// fire handlers
var eventData = {
// key: data
'foo': 'laLalaLa'
};
eventDispatcher.dispatch(eventData);