EventPublisher
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
import { Event, EventPublisher } from '../src/EventPublisher';
export class MyObservable<T> {
readonly start:Event<void>;
readonly update:Event<T>;
readonly complete:Event<void>;
private readonly _dispatcher:{
start:EventPublisher<void>,
update:EventPublisher<T>,
complete:EventPublisher<void>
};
constructor()
{
const start = new EventPublisher<void>(1);
const update = new EventPublisher<T>();
const complete = new EventPublisher<void>(1);
this._dispatcher = { start, update, complete };
this.start = start.event;
this.update = update.event;
this.complete = complete.event;
}
}
API
Event
type Listener<T> = (value: T) => void;
type Unsubscribe = () => void;
interface Event<T>
{
(listener: Listener<T>): Unsubscribe;
add(value: T): number;
remove(id: number): boolean;
register(value: T): number;
clear(): void;
}
EventPublisher
interface IEventPublisher<T>
{
publish(payload: T): void;
publishReverse(payload: T): void;
readonly event: Readonly<Event<T>>;
}