@boost/event
Version:
An event system with multiple emitter patterns.
109 lines (99 loc) • 2.68 kB
JavaScript
import { WILDCARD_SCOPE, EVENT_NAME_PATTERN } from './constants.mjs';
import { debug } from './debug.mjs';
import { EventError } from './EventError.mjs';
class BaseEvent {
constructor(name) {
this.listeners = new Map();
this.name = void 0;
this.name = this.validateName(name, 'name');
if (process.env.NODE_ENV !== "production") {
debug('New %S created: %s', this.constructor.name, name);
}
}
/**
* Remove all listeners from the event.
*/
clearListeners(scope) {
if (scope) {
this.getListeners(scope).clear();
} else {
this.listeners.clear();
}
return this;
}
/**
* Return a set of listeners for a specific event scope.
*/
getListeners(scope) {
const key = this.validateName(scope ?? WILDCARD_SCOPE, 'scope');
if (!this.listeners.has(key)) {
this.listeners.set(key, new Set());
}
return this.listeners.get(key);
}
/**
* Return a list of all scopes with listeners.
*/
getScopes() {
return [...this.listeners.keys()];
}
/**
* Register a listener to the event.
*/
listen(listener, scope) {
if (process.env.NODE_ENV !== "production") {
debug('Registering "%s" listener', this.name);
}
this.getListeners(scope).add(this.validateListener(listener));
return () => {
this.unlisten(listener, scope);
};
}
/**
* Register a listener to the event that only triggers once.
*/
once(listener, scope) {
const func = this.validateListener(listener);
const handler = (...args) => {
this.unlisten(handler);
return func(...args);
};
return this.listen(handler, scope);
}
/**
* Remove a listener from the event.
*/
unlisten(listener, scope) {
if (process.env.NODE_ENV !== "production") {
debug('Unregistering "%s" listener', this.name);
}
this.getListeners(scope).delete(listener);
return this;
}
/**
* Validate the listener is a function.
*/
validateListener(listener) {
if (process.env.NODE_ENV !== "production" && typeof listener !== 'function') {
throw new EventError('LISTENER_INVALID', [this.name]);
}
return listener;
}
/**
* Validate the name/scope match a defined pattern.
*/
validateName(name, type) {
if (type === 'scope' && name === WILDCARD_SCOPE) {
return name;
}
if (process.env.NODE_ENV !== "production" && !name.match(EVENT_NAME_PATTERN)) {
throw new EventError('NAME_INVALID', [type, name]);
}
return name;
}
/**
* Emit the event by executing all scoped listeners with the defined arguments.
*/
}
export { BaseEvent };
//# sourceMappingURL=BaseEvent.mjs.map