@posva/event-emitter
Version:
Type safe and light event emitter / pubsub class
56 lines • 1.36 kB
JavaScript
// src/event-emitter.ts
var EventEmitter = class {
/**
* A Map of event names to registered handler functions.
*/
all;
constructor(all) {
this.all = all || /* @__PURE__ */ new Map();
}
on(type, handler) {
if (!this.all.has(type)) {
this.all.set(type, []);
}
const handlers = this.all.get(type);
handlers.push(handler);
return () => handlers.splice(handlers.indexOf(handler) >>> 0, 1);
}
off(type, handler) {
if (!type) {
return this.all.clear();
}
const handlers = this.all.get(type);
if (handlers) {
if (handler) {
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
} else {
this.all.delete(type);
}
}
}
/**
* Invoke all handlers for the given type.
* If present, `'*'` handlers are invoked after type-matched handlers.
*
* Note: Manually firing `'*'` handlers is not supported.
*
* @param type The event type to invoke
* @param payload Any value to each handler
*/
emit(type, ...payload) {
let handlers = this.all.get(type);
handlers?.slice().map((handler) => {
handler(...payload);
});
handlers = this.all.get("*");
if (handlers) {
handlers.slice().map((handler) => {
handler(type, payload);
});
}
}
};
export {
EventEmitter
};
//# sourceMappingURL=index.js.map