Skip to content

Instantly share code, notes, and snippets.

@ternavsky
Created August 2, 2018 07:56
Show Gist options
  • Save ternavsky/8ec9c218079761144263d0596a82088c to your computer and use it in GitHub Desktop.
Save ternavsky/8ec9c218079761144263d0596a82088c to your computer and use it in GitHub Desktop.
Typescript Event Bus
import IEvent from "IEvent";
import IEventListener from "IEventListener";
export class EventEmitter
{
private listeners: { [key: string]: IEventListener[] } = {};
public on(event: Function, listener: IEventListener): void
{
if (!this.listeners[event.name]) this.listeners[event.name] = [];
this.listeners[event.name].push(listener);
}
public async emit(event: IEvent): Promise<void[]>
{
const listeners: IEventListener[] = this.listeners[event.constructor.name] || [];
return Promise.all(listeners.map(listener => listener.handle(event)));
}
public async fire(event: IEvent): Promise<void>
{
const listeners: IEventListener[] = this.listeners[event.constructor.name] || [];
for (let listener of listeners)
{
await listener.handle(event);
}
}
}
export const Emitter = new EventEmitter();
export default interface IEvent
{
//...
}
import IEvent from "IEvent";
export default interface IEventListener
{
handle(event: IEvent): Promise<void>;
}
import Emitter from 'Emitter';
import MyEvent from 'MyEvent';
import MyEventListener from 'MyEventListener';
Emitter.on(MyEvent, (new MyEventListener()));
Emitter.emit(new MyEvent());
import IEvent from "IEvent";
export default class MyEvent implements IEvent
{
//...
}
import MyEvent from "events/MyEvent";
import IEventListener from "events/IEventListener";
export default class MyEventListener implements IEventListener
{
constructor()
{
//...
}
async handle(event: MyEvent): Promise<void>
{
//...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment