From 28227bc1f7a6ba0f1eaa1f30a406105f88c8ef07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E7=BD=AA?= <531362022@qq.com> Date: Thu, 25 Feb 2021 23:10:23 +0800 Subject: [PATCH] fix: subscribeOnce unsubscribe from undefined object --- index.test.ts | 17 +++++++++++++++++ index.ts | 12 +++++++++++- package.json | 2 +- 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/index.test.ts b/index.test.ts index 579a828..043d9b5 100644 --- a/index.test.ts +++ b/index.test.ts @@ -236,3 +236,20 @@ it ('can release keeped handle', async () => { await sleep(5); expect(counter).to.equal(23); }); + +it ('can compose keep and subscribeOnce', async () => { + const topic = new Topic<{ + hello: (num: number) => void; + }>(); + + let counter = 0; + + const token1 = topic.keep('hello', true, 1); + topic.subscribeOnce('hello', (num) => { + counter += num; + }); + + expect(counter).to.equal(1); + + token1.release(); +}); diff --git a/index.ts b/index.ts index 73f9ec3..b0f216f 100644 --- a/index.ts +++ b/index.ts @@ -52,11 +52,21 @@ export class Topic { } subscribeOnce(name: K, fn: Callback): SubscribeToken { + let executed = false; + const token = this.subscribe(name, function () { fn.apply(null, arguments as unknown as Parameters); - token.unsubscribe(); + if (token) { + token.unsubscribe(); + } else { + executed = true; + } }); + if (executed) { + token.unsubscribe(); + } + return token; } diff --git a/package.json b/package.json index a74913f..49a3bfb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "topic", - "version": "2.1.0", + "version": "2.1.2", "description": "subscribe and publish your business.", "main": "index.cjs.js", "module": "index.module.js",