Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.