From bec4fff14aa1dda228f010a6a9d870dc05bd813d Mon Sep 17 00:00:00 2001 From: yuzheng14 <422450117@qq.com> Date: Thu, 29 Jun 2023 00:02:37 +0800 Subject: [PATCH 1/2] events: fix bug listenerCount don't compare wrapped listener When add listener by once, it will be wrapped into another function. And when pass listener and there is just one event listener added by once, it will return 0 even if passed listener equal wrapped event listener. Refs: https://github.com/nodejs/node/pull/46523 --- lib/events.js | 2 +- .../test-events-listener-count-with-listener.js | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/events.js b/lib/events.js index 89d32d681908c1..d61c7c1e40d844 100644 --- a/lib/events.js +++ b/lib/events.js @@ -845,7 +845,7 @@ function listenerCount(type, listener) { if (typeof evlistener === 'function') { if (listener != null) { - return listener === evlistener ? 1 : 0; + return listener === evlistener || listener === evlistener.listener ? 1 : 0; } return 1; diff --git a/test/parallel/test-events-listener-count-with-listener.js b/test/parallel/test-events-listener-count-with-listener.js index 080ce6d704513e..e269a319074aca 100644 --- a/test/parallel/test-events-listener-count-with-listener.js +++ b/test/parallel/test-events-listener-count-with-listener.js @@ -12,6 +12,18 @@ assert.strictEqual(EE.listenerCount('event'), 0); assert.strictEqual(EE.listenerCount('event', handler), 0); assert.strictEqual(EE.listenerCount('event', anotherHandler), 0); +EE.once('event', handler); + +assert.strictEqual(EE.listenerCount('event'), 1); +assert.strictEqual(EE.listenerCount('event', handler), 1); +assert.strictEqual(EE.listenerCount('event', anotherHandler), 0); + +EE.removeAllListeners('event') + +assert.strictEqual(EE.listenerCount('event'), 0); +assert.strictEqual(EE.listenerCount('event', handler), 0); +assert.strictEqual(EE.listenerCount('event', anotherHandler), 0); + EE.on('event', handler); assert.strictEqual(EE.listenerCount('event'), 1); From 71a76f9f3d8e3b58cf3bc594f05905bcab5c37bb Mon Sep 17 00:00:00 2001 From: yuzheng14 <422450117@qq.com> Date: Thu, 29 Jun 2023 13:24:37 +0800 Subject: [PATCH 2/2] test: fix style to pass lint --- test/parallel/test-events-listener-count-with-listener.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/parallel/test-events-listener-count-with-listener.js b/test/parallel/test-events-listener-count-with-listener.js index e269a319074aca..1696cb1c902cb9 100644 --- a/test/parallel/test-events-listener-count-with-listener.js +++ b/test/parallel/test-events-listener-count-with-listener.js @@ -18,7 +18,7 @@ assert.strictEqual(EE.listenerCount('event'), 1); assert.strictEqual(EE.listenerCount('event', handler), 1); assert.strictEqual(EE.listenerCount('event', anotherHandler), 0); -EE.removeAllListeners('event') +EE.removeAllListeners('event'); assert.strictEqual(EE.listenerCount('event'), 0); assert.strictEqual(EE.listenerCount('event', handler), 0);