2020-03-16 17:58:40 +00: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.
|
|
|
|
*/
|
2022-06-19 00:25:21 +00:00
|
|
|
on(type: string, handler: (...evt: any[]) => void) {
|
2020-03-16 17:58:40 +00:00
|
|
|
if (events.has(type)) {
|
2020-04-26 09:34:22 +00:00
|
|
|
events.get(type).push(handler);
|
2020-03-16 17:58:40 +00:00
|
|
|
} else {
|
2020-04-26 09:34:22 +00:00
|
|
|
events.set(type, [handler]);
|
2020-03-16 17:58:40 +00: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.
|
|
|
|
*/
|
2022-06-19 00:25:21 +00:00
|
|
|
off(type: string, handler: (...evt: any[]) => void) {
|
2020-03-16 17:58:40 +00:00
|
|
|
if (events.has(type)) {
|
2020-04-26 09:34:22 +00:00
|
|
|
events.set(
|
|
|
|
type,
|
2022-06-19 00:25:21 +00:00
|
|
|
events.get(type).filter((item: (...evt: any[]) => void) => item !== handler)
|
2020-04-26 09:34:22 +00:00
|
|
|
);
|
2020-03-16 17:58:40 +00: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.
|
|
|
|
*/
|
2022-06-19 00:25:21 +00:00
|
|
|
emit(type: string, ...evt: any) {
|
2020-03-16 17:58:40 +00:00
|
|
|
if (events.has(type)) {
|
2020-04-26 09:34:22 +00:00
|
|
|
events
|
|
|
|
.get(type)
|
|
|
|
.slice()
|
2022-06-19 00:25:21 +00:00
|
|
|
.map((handler: (...evts: any[]) => void) => {
|
2020-04-27 18:45:47 +00:00
|
|
|
handler(...evt);
|
2020-04-26 09:34:22 +00:00
|
|
|
});
|
2020-03-16 17:58:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default new EventBus();
|