Last active
January 8, 2019 15:16
-
-
Save javascripto/f56ba1d410a2a9ec55173126a09355d5 to your computer and use it in GitHub Desktop.
Imitação do EventEmitter usando no Angular para estudo do padrão Observable
This file contains hidden or 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
| interface Observable { | |
| subscribe: (fn?) => any; | |
| } | |
| class Subscription { | |
| constructor( | |
| private emitter: EventEmitter<any>, | |
| private index: number) {} | |
| unsubscribe() { | |
| this.emitter.unsubscribe(this.index); | |
| } | |
| } | |
| type closure = (...args: any) => any; | |
| class EventEmitter<T> implements Observable { | |
| protected subscribers: closure[] = []; | |
| protected unsubscriptions: number[] = []; | |
| emit(event?: T) { | |
| this.subscribers.forEach((subscriber, index) => { | |
| if (!this.unsubscriptions.includes(index)) | |
| subscriber(event); | |
| }); | |
| } | |
| subscribe(fn: (event?: T) => any ){ | |
| return new Subscription(this, this.subscribers.push(fn) -1); | |
| } | |
| unsubscribe(index) { | |
| this.unsubscriptions.push(index); | |
| } | |
| } | |
| // Testando | |
| const emitter = new EventEmitter<any>(); | |
| const subscription1 = emitter.subscribe(() => console.log('evento emitido')); | |
| const subscription2 = emitter.subscribe((event: any) => console.log(event + event)); | |
| const subscription3 = emitter.subscribe((event: any) => console.log(event * 4)); | |
| subscription2.unsubscribe(); | |
| emitter.emit(123); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment