Skip to content

Instantly share code, notes, and snippets.

@smelukov
Created July 23, 2020 17:21
Show Gist options
  • Save smelukov/25cf3900197bc868705e702807fe6039 to your computer and use it in GitHub Desktop.
Save smelukov/25cf3900197bc868705e702807fe6039 to your computer and use it in GitHub Desktop.
type Handler<TArg> = (arg: TArg) => void
type Events = {
foo: string,
bar: number
}
class EventEmitter<TEvent> {
private listeners: Map<keyof TEvent, Set<Handler<any>>> = new Map();
on<T extends keyof TEvent>(type: T, handler: Handler<TEvent[T]>) {
let handlers = this.listeners.get(type);
if (!handlers) {
handlers = new Set();
this.listeners.set(type, handlers);
}
handlers.add(handler);
}
emit<T extends keyof TEvent>(type: T, arg: TEvent[T]) {
const handlers = this.listeners.get(type);
if (handlers) {
for (const handler of handlers) {
handler(arg);
}
}
}
}
const emitter = new EventEmitter<Events>();
emitter.on('foo', (arg) => {
console.log('!!!', arg);
})
emitter.emit('foo', 'bar');
emitter.emit('bar', 124);
import Event from '@wdxlab/events';
class Gun {
readonly eventShoot = new Event<Gun, number>();
readonly eventReloaded = new Event<Gun, number>();
private capacity: number;
private bullets = 0;
constructor(capacity: number) {
this.capacity = capacity;
this.reload();
}
shoot() {
if (this.bullets) {
this.eventShoot.emit(this, --this.bullets);
}
}
reload() {
this.bullets = this.capacity;
this.eventReloaded.emit(this, this.bullets);
}
}
const gun = new Gun(5);
gun.eventShoot.on((sender, remainBullets) => {
console.log('remain bullets', remainBullets);
if (!remainBullets) {
sender.reload();
}
});
gun.eventReloaded.on((sender, remainBullets) => console.log('reloaded. remain bullets', remainBullets));
for (let i = 0; i < 100; i++) {
gun.shoot();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment