Skip to content

Instantly share code, notes, and snippets.

@msbrime
Created August 2, 2017 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msbrime/b9801192dcb225fe0e0a2346a6155d47 to your computer and use it in GitHub Desktop.
Save msbrime/b9801192dcb225fe0e0a2346a6155d47 to your computer and use it in GitHub Desktop.
A general purpose event dispatcher
/** @constructor */
function Dispatcher(context, events) {
this.ctx = context;
this.events = events;
this.listeners = {};
}
/**
* Adds an event listener to an event
*
* @param {string} event the name of the event to be listened to
* @param {function} fn the callback to fire when the event is emitted
*/
Dispatcher.prototype.addEventListener = function (event, fn) {
if (this.events.indexOf(event) > -1) {
if (!this.listeners.hasOwnProperty(event)) {
this.listeners[event] = [];
}
this.listeners[event].push(fn);
}
}
/**
* Removes a previosly registered event listener from an event
*
* @param {string} event the name of the event
* @param {function} fn the callback to be removed
*/
Dispatcher.prototype.removeEventListener = function (event, fn) {
if (this.listeners.hasOwnProperty(event)) {
this.listeners[event] = this.listeners[event].filter(function (listener) {
return listener.toString() !== fn.toString();
});
}
}
/**
* Emits an event
*
* @param {string} event the event to be emitted
* @param {array} [args] arguments to pass to the callback
*/
Dispatcher.prototype.emit = function (event, args) {
var dispatcher = this;
if (this.listeners.hasOwnProperty(event)) {
this.listeners[event].forEach(function (listener) {
listener.apply(dispatcher.ctx, args);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment