Skip to content

Instantly share code, notes, and snippets.

@malbarmavi
Created November 6, 2018 08:51
Show Gist options
  • Save malbarmavi/fc4d45b54c613de8946bc29d23c1f73a to your computer and use it in GitHub Desktop.
Save malbarmavi/fc4d45b54c613de8946bc29d23c1f73a to your computer and use it in GitHub Desktop.
Event Emitter with TypeScript
class EventEmitter<T> {
private _subscription: any[] = []
constructor() {
}
subscribe(habdler) {
this._subscription.push(habdler)
}
undubscribe(handler) {
let index = this._subscription.indexOf(handler)
this._subscription.splice(index, 1)
}
emit(value: T) {
this._subscription.forEach(h => {
if (typeof h === 'function') {
h(value);
}
})
}
}
class Person {
onRun: EventEmitter<string>;
constructor(public name: string) {
this.onRun = new EventEmitter();
}
running() {
this.onRun.emit(`${this.name} => I 'm running..`)
}
}
let me = new Person('me');
let you = new Person('you');
you.onRun.subscribe(s => console.log(s));
me.onRun.subscribe(s => {
console.log(s);
you.running();
});
setTimeout(() => {
me.running();
}, 2500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment