5.0.0 • Published 9 months ago

typed-emitters v5.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

typed-emitters | Simple and convenient event emitters with separate interfaces for consumers.

100% TypeScript, no deps.

Install

npm install typed-emitters

Single-event emitter

Provider

import { createSingleEventEmitter } from "typed-emitters";
const emitter = // Or private class field
    createSingleEventEmitter<
        [string, number] // Multiple args are supported
    >();

// Share the public interface
export const event = this.emitter.source; // Or public class field
emitter.emit("Test string", 1); // Type checking

Consumer

// Consumer has access only to the public interface (can listen but not emit)

// The type of args is [string, number]
event.addListener((...args) => {
    console.log(args);
});

Multi-event emitter

Provider

import { createMultiEventEmitter } from "typed-emitters";
const emitter = // Or private class field
    createMultiEventEmitter<{
        'type1': [number],
        'type2' [string, number]
    }>();

// Share the public interface
export const events = this.emitter.source; // Or public class field
emitter.emit("type1", 1); // Type checking
emitter.emit("type2", "Test string", 1); // Type checking

Consumer

// Consumer has access only to the public interface (can listen but not emit)

// 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 listeners

emitter.hasListeners();
emitter.hasListeners("type1");

Removing all listeners

emitter.removeAllListeners();
emitter.removeAllListeners("type1");

Exported types

  • SingleEventEmitter<Args>
  • SingleEventSource<Args>
  • MultiEventEmitter<ArgsByEventName>
  • MultiEventSource<ArgsByEventName>
5.0.0

9 months ago

4.1.0

9 months ago

4.0.0

9 months ago

4.1.1

9 months ago

3.0.5

1 year ago

3.0.4

1 year ago

3.0.3

1 year ago

3.0.2

1 year ago

3.0.1

1 year ago

3.0.0

1 year ago

2.0.2

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

1.0.7

1 year ago

1.0.5

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago