Ecosyste.ms: Awesome

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

Awesome Lists | Featured Topics | Projects

https://github.com/electricessence/eventpublisher

A strongly typed protected event creator/publisher/signaler for use with TypeScript and JavaScript.
https://github.com/electricessence/eventpublisher

Last synced: 1 day ago
JSON representation

A strongly typed protected event creator/publisher/signaler for use with TypeScript and JavaScript.

Awesome Lists containing this project

README

        

# EventPublisher

[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](https://github.com/electricessence/EventPublisher/blob/master/LICENSE)
[![npm version](https://img.shields.io/npm/v/event-publisher.svg?style=flat-square)](https://www.npmjs.com/package/event-publisher)

A strongly typed protected event creator/publisher/signaler for use with TypeScript and JavaScript.

## Purpose
* Provides an API that separates event listening/subscribing from dispatching/publishing.
* Simplifies adding events to any object.

## Example
```ts
import { Event, EventPublisher } from '../src/EventPublisher';

export class MyObservable {

readonly start:Event;
readonly update:Event;
readonly complete:Event;

private readonly _dispatcher:{
start:EventPublisher,
update:EventPublisher,
complete:EventPublisher
};

constructor()
{
const start = new EventPublisher(1);
const update = new EventPublisher();
const complete = new EventPublisher(1);
this._dispatcher = { start, update, complete };
this.start = start.event;
this.update = update.event;
this.complete = complete.event;
}
}
```

## API

### Event
```ts
type Listener = (value: T) => void;
type Unsubscribe = () => void;

interface Event
{
/**
* Adds a listener and return an unsubscribe function.
* @param listener
*/
(listener: Listener): Unsubscribe;

/**
* Add an entry to the end of the registry.
* @param value
*/

add(value: T): number;
/**
* Remove an entry.
* @param id
*/
remove(id: number): boolean;

/**
* Adds an entry to the registry if it doesn't exist.
* @param value
*/
register(value: T): number;

/**
* Clears all entries.
*/
clear(): void;
}
```

### EventPublisher
```ts
interface IEventPublisher
{
publish(payload: T): void;
publishReverse(payload: T): void;

readonly event: Readonly>;
}
```