Last active
December 4, 2022 01:28
-
-
Save librz/eb1968420dcb5a71b6d970dd8dabcf5d to your computer and use it in GitHub Desktop.
naive example code for "topic based publish/subscribe model"
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
| // naive example code for "topic based publish/subscribe model" | |
| // this is just to illustrate the idea, feature is incomplete, do NOT use in production | |
| // reference: https://github.com/mroderick/PubSubJS | |
| type TopicHandler = (data?: any) => void; | |
| interface ISubscriber { | |
| topic: string; | |
| handler: TopicHandler | |
| } | |
| class PubSub { | |
| static topics: string[] = []; | |
| static subsribers: Array<ISubscriber> = []; | |
| static subscribe = (topic: string, handler: TopicHandler) => { | |
| if (!PubSub.topics.includes(topic)) { | |
| PubSub.topics.push(topic) | |
| } | |
| PubSub.subsribers.push({ topic, handler }) | |
| } | |
| static publish = (topic: string, data: any) => { | |
| if (!PubSub.topics.includes(topic)) { | |
| PubSub.topics = PubSub.topics.concat(topic) | |
| } | |
| const topicSubsribers = PubSub.subsribers.filter(it => it.topic === topic) | |
| topicSubsribers.forEach(it => { | |
| it.handler(data) | |
| }) | |
| } | |
| } | |
| let balance: number = 0; | |
| PubSub.subscribe("receive", (dollar: number) => { | |
| balance += dollar; | |
| console.log(`Received ${dollar} dollars. Current balance is ${balance}`) | |
| }) | |
| PubSub.subscribe("withdraw", (dollar: number) => { | |
| balance -= dollar; | |
| console.log(`Withdrawed ${dollar} dollars. Current balance is ${balance}`) | |
| }) | |
| PubSub.publish("receive", 100) | |
| PubSub.publish("receive", 50) | |
| setTimeout(() => { | |
| PubSub.publish("withdraw", 30) | |
| }, 1000); | |
| setTimeout(() => { | |
| PubSub.publish("withdraw", 40) | |
| }, 2000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment