From 0c8539e336bfe81c816a85dce71894dbef9ab371 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 da2097dfbd81e2..f42a11ab3e701d 100644 --- a/lib/events.js +++ b/lib/events.js @@ -847,7 +847,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);