Created
August 2, 2017 23:12
-
-
Save msbrime/b9801192dcb225fe0e0a2346a6155d47 to your computer and use it in GitHub Desktop.
A general purpose event dispatcher
This file contains hidden or 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
/** @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