From 6e2cbe0cf1773a70bd2f5f4ea0bb6496f0607889 Mon Sep 17 00:00:00 2001 From: yuzheng14 <55919198+yuzheng14@users.noreply.github.com> Date: Mon, 10 Jul 2023 14:33:51 +0800 Subject: [PATCH] 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 PR-URL: https://github.com/nodejs/node/pull/48592 Reviewed-By: Luigi Pinca Reviewed-By: Paolo Insogna Reviewed-By: Minwoo Jung --- 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 41c902be5905be..0ec374bc814497 100644 --- a/lib/events.js +++ b/lib/events.js @@ -850,7 +850,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..1696cb1c902cb9 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);