All files / patterns/observer/src index.ts

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29                    1x 5x     3x       1x 1x       1x 1x        
export interface ObservableInterface {
    attach(observer: ObserverInterface): void;
    detach(observer: ObserverInterface): void;
    notify(message: string): void;
}
 
export interface ObserverInterface {
    update(subject: ObservableInterface, message: string): void;
}
 
export abstract class Observable implements ObservableInterface {
    protected observers: ObserverInterface[] = [];
 
    public attach(observer: ObserverInterface): void {
        this.observers.push(observer);
    }
 
    public detach(observer: ObserverInterface): void {
        const observerIndex = this.observers.indexOf(observer);
        this.observers.splice(observerIndex, 1);
    }
 
    public notify(message: string): void {
        this.observers.forEach((observer): void =>
            observer.update(this, message),
        );
    }
}