Skip to content

Instantly share code, notes, and snippets.

@yaodong
Created August 10, 2016 19:38
Show Gist options
  • Save yaodong/f4fc9e84368b02718578ef9eabcab1d8 to your computer and use it in GitHub Desktop.
Save yaodong/f4fc9e84368b02718578ef9eabcab1d8 to your computer and use it in GitHub Desktop.
simple js event manager
const $ = require('jquery');
class EventManager {
constructor(handlers) {
this._handlers = {};
if (handlers) {
$.each(handlers, (name, cb) => {
this.listen(name, cb);
});
}
}
listen(eventName, cb) {
if (typeof eventName === "string") {
if (!this._handlers[eventName]) {
this._handlers[eventName] = []
}
if ($.isArray(cb)) {
this._handlers[eventName].push(...cb);
} else {
this._handlers[eventName].push(cb);
}
} else {
$.each(eventName, (eventName, cb) => {
this.listen(eventName, cb);
});
}
}
trigger(eventName, payload = []) {
if (!$.isArray(payload)) {
payload = [payload];
}
if (this._handlers[eventName]) {
this._handlers[eventName].map((handler) => {
handler(...payload);
});
}
}
}
module.exports = EventManager;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment