Skip to content

Instantly share code, notes, and snippets.

@sangheestyle
Created November 17, 2018 20:45
Show Gist options
  • Save sangheestyle/5ff891892ca0f13b2a287add15a8964c to your computer and use it in GitHub Desktop.
Save sangheestyle/5ff891892ca0f13b2a287add15a8964c to your computer and use it in GitHub Desktop.
Practice the observer pattern in typescript
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');
export interface ISubject {
subscribe: Function;
unsubscribe: Function;
notify: Function;
}
export interface IObserver {
onSubscribe: Function
}
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}`);
}
}
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));
}
}
{
"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