tav-media
Version:
Cross platform media editing framework
55 lines (54 loc) • 1.73 kB
JavaScript
/**
* EventManager is a class to manage event listeners.
*/
export class EventManager {
constructor() {
this.listenersMap = {};
}
/**
* Listen to an event.
* @param eventName The name of the event to listen to.
* @param listener The callback function to be called when the event is emitted.
* @returns void
*/
on(eventName, listener) {
if (this.listenersMap[eventName] === undefined) {
this.listenersMap[eventName] = [];
}
this.listenersMap[eventName].push(listener);
return;
}
/**
* Remove a listener from an event.
* @param eventName The name of the event to listen to.
* @param listener The callback function to be called when the event is emitted.
* @returns void
*/
off(eventName, listener) {
const listenerList = this.listenersMap[eventName];
if (listenerList === undefined)
return;
if (listener === undefined) {
delete this.listenersMap[eventName];
return;
}
const index = listenerList.findIndex((fn) => fn === listener);
listenerList.splice(index, 1);
return;
}
/**
* Emit an event.
* @param eventName The name of the event to listen to.
* @param payload The payload to be passed to the listener.
* @returns true if the event has listeners, false otherwise.
*/
emit(eventName, ...payload) {
const listenerList = this.listenersMap[eventName];
if (listenerList === undefined || listenerList.length < 1)
return false;
for (const listener of listenerList) {
listener(...payload);
}
return true;
}
}