Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/keupoz/typed-event-dispatcher

Typed Event dispatcher for TypeScript
https://github.com/keupoz/typed-event-dispatcher

Last synced: about 1 month ago
JSON representation

Typed Event dispatcher for TypeScript

Awesome Lists containing this project

README

        

# Typed EventDispatcher

Just a simple strictly typed event dispatcher

## Installation

```bash
npm install @keupoz/typed-event-dispatcher
```

## Usage

```typescript
import { EventDispatcher } from "@keupoz/typed-event-dispatcher";

// EventDispatcher accepts any type
// but it should be a record of data types associated with event names
export interface IFooEvents {
init: null;
bar: {
type: string;
data: any;
};
}

export class Foo extends EventDispatcher {
constructor() {
super();

this.dispatch("init", null);
}

public bar(data: any): void {
this.dispatch("bar", {
type: "test data",
data: data,
});
}
}

const foo = new Foo();

// data is null
foo.on("init", () => {
console.log("Foo is initialized");
});

// data is { type: string; data: any; }
foo.on("bar", (data) => {
console.log(`Got data of type '${data.type}'`, data.data);
});

foo.bar(["some", "random", "data"]);

// Remove all listeners
foo.dispose();
```