Last active
November 7, 2020 10:29
-
-
Save scsskid/ed6e8c04934e372db70579fa1cf4e77f to your computer and use it in GitHub Desktop.
[Event Bus] from the Lounge IRC Client - https://github.com/thelounge/thelounge/blob/master/client/js/eventbus.js
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 events = new Map(); | |
class EventBus { | |
/** | |
* Register an event handler for the given type. | |
* | |
* @param {String} type Type of event to listen for. | |
* @param {Function} handler Function to call in response to given event. | |
*/ | |
on(type, handler) { | |
if (events.has(type)) { | |
events.get(type).push(handler); | |
} else { | |
events.set(type, [handler]); | |
} | |
} | |
/** | |
* Remove an event handler for the given type. | |
* | |
* @param {String} type Type of event to unregister `handler` from. | |
* @param {Function} handler Handler function to remove. | |
*/ | |
off(type, handler) { | |
if (events.has(type)) { | |
events.set( | |
type, | |
events.get(type).filter((item) => item !== handler) | |
); | |
} | |
} | |
/** | |
* Invoke all handlers for the given type. | |
* | |
* @param {String} type The event type to invoke. | |
* @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler. | |
*/ | |
emit(type, ...evt) { | |
if (events.has(type)) { | |
events | |
.get(type) | |
.slice() | |
.map((handler) => { | |
handler(...evt); | |
}); | |
} | |
} | |
} | |
export default new EventBus(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment