import {HttpError} from "./http";
+type Listener = (data: any) => void;
+
export class EventManager {
- protected listeners: Record<string, ((data: {}) => void)[]> = {};
+ protected listeners: Record<string, Listener[]> = {};
protected stack: {name: string, data: {}}[] = [];
/**
* Emit a custom event for any handlers to pick-up.
*/
- emit(eventName: string, eventData: {}): void {
+ emit(eventName: string, eventData: {} = {}): void {
this.stack.push({name: eventName, data: eventData});
const listenersToRun = this.listeners[eventName] || [];
/**
* Listen to a custom event and run the given callback when that event occurs.
*/
- listen(eventName: string, callback: (data: {}) => void): void {
+ listen<T>(eventName: string, callback: (data: T) => void): void {
if (typeof this.listeners[eventName] === 'undefined') this.listeners[eventName] = [];
this.listeners[eventName].push(callback);
}
+ /**
+ * Remove an event listener which is using the given callback for the given event name.
+ */
+ remove(eventName: string, callback: Listener): void {
+ const listeners = this.listeners[eventName] || [];
+ const index = listeners.indexOf(callback);
+ if (index !== -1) {
+ listeners.splice(index, 1);
+ }
+ }
+
/**
* Emit an event for public use.
* Sends the event via the native DOM event handling system.
/**
* Notify of standard server-provided validation errors.
*/
- showValidationErrors(responseErr: {status?: number, data?: object}): void {
- if (!responseErr.status) return;
+ showValidationErrors(responseErr: HttpError): void {
if (responseErr.status === 422 && responseErr.data) {
const message = Object.values(responseErr.data).flat().join('\n');
this.error(message);