@posva/event-emitter
Version:
Type safe and light event emitter / pubsub class
83 lines (81 loc) • 2.39 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
EventEmitter: () => EventEmitter
});
module.exports = __toCommonJS(index_exports);
// 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);
});
}
}
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
EventEmitter
});
//# sourceMappingURL=index.cjs.map