From 567f8d8caf4948a6d02aa809db6b0285b6347673 Mon Sep 17 00:00:00 2001 From: Benjamin Gruenbaum Date: Fri, 6 Nov 2020 12:05:08 +0200 Subject: [PATCH] events: getEventListeners static PR-URL: https://github.com/nodejs/node/pull/35991 Reviewed-By: James M Snell Reviewed-By: Matteo Collina --- doc/api/events.md | 34 ++++++++++++++++++ lib/events.js | 26 +++++++++++++- lib/internal/event_target.js | 2 ++ .../test-events-static-geteventlisteners.js | 36 +++++++++++++++++++ 4 files changed, 97 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-events-static-geteventlisteners.js diff --git a/doc/api/events.md b/doc/api/events.md index 17420a249be731..b593cfac44969f 100644 --- a/doc/api/events.md +++ b/doc/api/events.md @@ -829,6 +829,40 @@ class MyClass extends EventEmitter { } ``` +## `events.getEventListeners(emitterOrTarget, eventName)` + +* `emitterOrTarget` {EventEmitter|EventTarget} +* `eventName` {string|symbol} +* Returns: {Function[]} + +Returns a copy of the array of listeners for the event named `eventName`. + +For `EventEmitter`s this behaves exactly the same as calling `.listeners` on +the emitter. + +For `EventTarget`s this is the only way to get the event listeners for the +event target. This is useful for debugging and diagnostic purposes. + +```js +const { getEventListeners, EventEmitter } = require('events'); + +{ + const ee = new EventEmitter(); + const listener = () => console.log('Events are fun'); + ee.on('foo', listener); + getEventListeners(ee, 'foo'); // [listener] +} +{ + const et = new EventTarget(); + const listener = () => console.log('Events are fun'); + ee.addEventListener('foo', listener); + getEventListeners(ee, 'foo'); // [listener] +} +``` + ## `events.once(emitter, name[, options])`