From 3152b126d657c3c3d5f84c5556f8b994ee3b1701 Mon Sep 17 00:00:00 2001 From: yuzheng14 <422450117@qq.com> Date: Thu, 29 Jun 2023 00:02:37 +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 --- 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);