@webeach/event-manager
Version:
EventManager is a library for simplifying event handling in JavaScript
100 lines (97 loc) • 3.68 kB
JavaScript
import { validateTargetType, validateEventType, validateHandlerList, validateEventObject } from './utils.js';
class EventManager {
handlerSerializedMap = new Map();
target;
constructor(target, initialHandlerMap = null) {
if (!validateTargetType(target)) {
throw new TypeError('Parameter "target" must be a EventTarget');
}
this.target = target;
this.add = this.add.bind(this);
this.capture = this.capture.bind(this);
this.once = this.once.bind(this);
this.remove = this.remove.bind(this);
this.trigger = this.trigger.bind(this);
if (initialHandlerMap !== null) {
for (const eventType in initialHandlerMap) {
if (Object.prototype.hasOwnProperty.call(initialHandlerMap, eventType)) {
this.add(eventType, initialHandlerMap[eventType]);
}
}
}
}
add(type, handlers, options = {}) {
if (!validateEventType(type)) {
throw new TypeError('Parameter "type" must be a Event');
}
if (!validateHandlerList(handlers)) {
throw new TypeError('Parameter "handlers" must be a EventHandlerMap');
}
if (!this.handlerSerializedMap.has(type)) {
this.handlerSerializedMap.set(type, []);
}
const finalOptions = Object.freeze({
capture: options.capture ?? false,
once: options.once ?? false,
});
const eventHandlerList = Array.isArray(handlers) ? handlers : [handlers];
const targetHandlerList = this.handlerSerializedMap.get(type);
eventHandlerList.forEach((handler) => {
targetHandlerList.push([handler, finalOptions]);
this.target.addEventListener(type, handler, finalOptions);
});
return this;
}
capture(type, handlers) {
return this.add(type, handlers, {
capture: true,
});
}
once(type, handlers) {
return this.add(type, handlers, {
once: true,
});
}
remove(type = null) {
if (type === null) {
return this.removeAllHandlers();
}
const eventTypeList = Array.isArray(type) ? type : [type];
eventTypeList.forEach((eventType) => {
if (!validateEventType(eventType)) {
throw new TypeError('Parameter "type" must be a Event');
}
const eventHandlerList = this.handlerSerializedMap.get(eventType) ?? null;
if (eventHandlerList !== null) {
eventHandlerList.forEach(([handler, options]) => {
this.target.removeEventListener(eventType, handler, options);
});
this.handlerSerializedMap.delete(eventType);
}
});
return this;
}
trigger(...params) {
const [event, detail] = params;
if (validateEventType(event)) {
this.target.dispatchEvent(new CustomEvent(event, { detail }));
return this;
}
if (validateEventObject(event)) {
this.target.dispatchEvent(event);
return this;
}
throw new TypeError('Parameter "event" must be a Event');
}
removeAllHandlers() {
this.handlerSerializedMap.forEach((targetHandlerList, eventType) => {
targetHandlerList.forEach(([handler, options]) => {
this.target.removeEventListener(eventType, handler, options);
});
});
this.handlerSerializedMap.clear();
return this;
}
}
export { EventManager };
//# sourceMappingURL=EventManager.js.map