Skip to content

Instantly share code, notes, and snippets.

@czarpino
Last active August 29, 2015 14:03
Show Gist options
  • Save czarpino/80ceccc74a50403321f1 to your computer and use it in GitHub Desktop.
Save czarpino/80ceccc74a50403321f1 to your computer and use it in GitHub Desktop.

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 || {});

Usage

// binding handlers to events
eventDispatcher.register('foo', function (data) {
    alert(data);
});

// fire handlers
var eventData = {

    // key: data
    'foo': 'laLalaLa'
};
eventDispatcher.dispatch(eventData);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment