Created
August 10, 2016 19:38
-
-
Save yaodong/f4fc9e84368b02718578ef9eabcab1d8 to your computer and use it in GitHub Desktop.
simple js event manager
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
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