From b8acd0a3e4515593bad445426f86b9e35ee6a59d Mon Sep 17 00:00:00 2001 From: sealday Date: Wed, 3 Jul 2024 15:21:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20pubsub.ts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pubsub.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 pubsub.ts diff --git a/pubsub.ts b/pubsub.ts new file mode 100644 index 0000000..ef57309 --- /dev/null +++ b/pubsub.ts @@ -0,0 +1,30 @@ +interface PubSub { + subscribe(event: string, listener: (data: any) => void): void; + unsubscribe(event: string, listener: (data: any) => void): void; + publish(event: string, data: any): void; +} + +// 创建 PubSub 实例 +const pubSub = new SimplePubSub(); + +// 定义订阅者 +const subscriber1 = (data: any) => { + console.log(`Subscriber 1 received: ${data}`); +}; + +const subscriber2 = (data: any) => { + console.log(`Subscriber 2 received: ${data}`); +}; + +// 订阅事件 +pubSub.subscribe('event1', subscriber1); +pubSub.subscribe('event1', subscriber2); + +// 发布事件 +pubSub.publish('event1', 'Hello, World!'); + +// 取消订阅 +pubSub.unsubscribe('event1', subscriber1); + +// 发布事件 +pubSub.publish('event1', 'Hello again!'); \ No newline at end of file