thelounge/client/js/eventbus.js

52 lines
1.1 KiB
JavaScript
Raw Normal View History

2020-03-16 18:58:40 +01:00
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)) {
2020-04-26 11:34:22 +02:00
events.get(type).push(handler);
2020-03-16 18:58:40 +01:00
} else {
2020-04-26 11:34:22 +02:00
events.set(type, [handler]);
2020-03-16 18:58:40 +01:00
}
}
/**
* 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)) {
2020-04-26 11:34:22 +02:00
events.set(
type,
events.get(type).filter((item) => item !== handler)
);
2020-03-16 18:58:40 +01:00
}
}
/**
* 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) {
2020-03-16 18:58:40 +01:00
if (events.has(type)) {
2020-04-26 11:34:22 +02:00
events
.get(type)
.slice()
.map((handler) => {
handler(...evt);
2020-04-26 11:34:22 +02:00
});
2020-03-16 18:58:40 +01:00
}
}
}
export default new EventBus();