@servie/events
Version:
Tiny type-safe event emitter
53 lines • 1.22 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.once = exports.Emitter = exports.ALL_EVENTS = void 0;
/**
* All events are emitted using this key.
*/
exports.ALL_EVENTS = Symbol("ALL_EVENTS");
/**
* Create an `off` function given an input.
*/
function add(stack, value) {
stack.add(value);
return function off() {
return stack.delete(value);
};
}
/**
* Emit an event.
*/
function emit(stack, ...args) {
if (stack)
for (const { fn } of stack)
fn(...args);
}
/**
* Type-safe event emitter.
*/
class Emitter {
constructor() {
this.$ = Object.create(null);
}
on(type, fn) {
const stack = (this.$[type] = this.$[type] || new Set());
return add(stack, { fn });
}
emit(type, ...args) {
emit(this.$[type], ...args);
emit(this.$[exports.ALL_EVENTS], { type, args });
}
}
exports.Emitter = Emitter;
/**
* Helper to listen to an event once only.
*/
function once(events, type, callback) {
const off = events.on(type, function once(...args) {
off();
return callback(...args);
});
return off;
}
exports.once = once;
//# sourceMappingURL=index.js.map