Skip to content

Commit

Permalink
fix: subscribeOnce unsubscribe from undefined object
Browse files Browse the repository at this point in the history
  • Loading branch information
fwh1990 committed Feb 25, 2021
1 parent f7bae1d commit 28227bc
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
17 changes: 17 additions & 0 deletions index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
12 changes: 11 additions & 1 deletion index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,21 @@ export class Topic<T extends CommonObject> {
}

subscribeOnce<K extends keyof T>(name: K, fn: Callback<T, K>): SubscribeToken {
let executed = false;

const token = this.subscribe(name, function () {
fn.apply(null, arguments as unknown as Parameters<T[K]>);
token.unsubscribe();
if (token) {
token.unsubscribe();
} else {
executed = true;
}
});

if (executed) {
token.unsubscribe();
}

return token;
}

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down

0 comments on commit 28227bc

Please sign in to comment.