Created
April 26, 2024 13:15
-
-
Save dkacper/c79a53beb4574f5ce2c36e8b4fe80d1d to your computer and use it in GitHub Desktop.
Publish-subscriber. Implementation of observer pattern in 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
type Subscriber<TData> = (data: TData) => void; | |
interface IPublisher<TEvent, TData> { | |
subscribe(event?: TEvent): (subscriber: Subscriber<TData>) => () => void; | |
notify(event: TEvent, data: TData): void; | |
} | |
export class Publisher<TEvent, TData> implements IPublisher<TEvent, TData> { | |
protected subscribers: { event: TEvent; subscriber: Subscriber<TData> }[] = []; | |
public subscribe = (event?: TEvent) => (subscriber: Subscriber<TData>) => { | |
this.subscribers.push({ event, subscriber }); | |
return () => { | |
this.subscribers = this.subscribers.filter( | |
(sub) => subscriber !== sub.subscriber | |
); | |
}; | |
}; | |
public notify = (event: TEvent, data: TData) => { | |
for (const sub of this.subscribers) { | |
if (sub.event === event || !sub.event) { | |
sub.subscriber(data); | |
} | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment