Created
November 6, 2018 08:51
-
-
Save malbarmavi/fc4d45b54c613de8946bc29d23c1f73a to your computer and use it in GitHub Desktop.
Event Emitter with TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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