Created
November 17, 2018 20:45
-
-
Save sangheestyle/5ff891892ca0f13b2a287add15a8964c to your computer and use it in GitHub Desktop.
Practice the observer pattern in typescript
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
import { Subject } from "./subject"; | |
import { Observer } from "./observer"; | |
const subject = new Subject(); | |
const observer1 = new Observer('John'); | |
const observer2 = new Observer('Tae'); | |
const observer3 = new Observer('Jin'); | |
subject.subscribe(observer1); | |
subject.subscribe(observer2); | |
subject.subscribe(observer3); | |
subject.notify('hello'); |
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
export interface ISubject { | |
subscribe: Function; | |
unsubscribe: Function; | |
notify: Function; | |
} | |
export interface IObserver { | |
onSubscribe: Function | |
} |
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
import { IObserver } from "./interface"; | |
export class Observer implements IObserver { | |
private name: string; | |
constructor(name: string) { | |
this.name = name; | |
} | |
onSubscribe(data): void { | |
console.log(`-> ${this.name}: data received ${data}`); | |
} | |
} |
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
import { ISubject, IObserver } from "./interface"; | |
export class Subject implements ISubject { | |
private subscribers: Array<IObserver> = []; | |
subscribe(observer: IObserver): void { | |
this.subscribers.push(observer); | |
} | |
unsubscribe(observer: IObserver): void { | |
this.subscribers.filter(s => s != observer); | |
} | |
notify(data): void { | |
this.subscribers.map(s => s.onSubscribe(data)); | |
} | |
} |
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
Show hidden characters
{ | |
"forceConsistentCasingInFileNames": true, | |
"noImplicitReturns": true, | |
"strict": true, | |
"noUnusedLocals": true, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment