typed-emitters
v6.0.3
Published
Simple / Typed / Universal / Lightweight / Dependency-free event emitters
Downloads
464
Maintainers
Readme
Install
npm install typed-emitters
Single-event emitter
Create emitter
import { createTypedEmitter } from "typed-emitters";
const emitter =
createTypedEmitter<
[string, number] // Multiple args are supported
>();
// Share the public interface
export const event = this.emitter.source;
emitter.emit("Test string", 1); // Type checking
Listen to events
// The source object allows listening to events but not emitting them
// The type of args is [string, number]
event.addListener((...args) => {
console.log(args);
});
Multi-event emitter
Create emitter
import { createTypedMultiEmitter } from "typed-emitters";
const emitter =
createTypedMultiEmitter<{
'type1': [number],
'type2' [string, number]
}>();
// Share the public interface
export const events = this.emitter.source;
emitter.emit("type1", 1); // Type checking
emitter.emit("type2", "Test string", 1); // Type checking
Listen to events
// The source object allows listening to events but not emitting them
// The type of value is number
events.addListener("type1", (value) => {
console.log(value);
});
// The type of args is [string, number]
events.addListener("type2", (...args) => {
console.log(args);
});
Unsubscribing
// Option 1
event.removeListener(yourListener);
// Option 2
const dispose = event.addListener((...args) => {
console.log(args);
});
dispose();
Other
Check if an emitter has any listeners
emitter.checkForListeners();
emitter.checkForListeners("type1");
Removing all listeners
emitter.removeAllListeners();
emitter.removeAllListeners("type1");
Exported types
TypedEventEmitter<Args>
TypedEventSource<Args>
TypedMultiEventEmitter<ArgsByEventName>
TypedMultiEventSource<ArgsByEventName>