Skip to content

Commit

Permalink
events: add listEvents() method
Browse files Browse the repository at this point in the history
Per nodejs#1817, there are many modules
that currently abuse the private `_events` property on EventEmitter.
One of the ways it is used is to determine if a particular event is
being listened for. This adds a simple `listEvents()` method that
returns an array of the events with currently registered listeners.
  • Loading branch information
jasnell committed Mar 12, 2016

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent 59b7c0e commit e9b1ea9
Showing 3 changed files with 41 additions and 0 deletions.
14 changes: 14 additions & 0 deletions doc/api/events.markdown
Original file line number Diff line number Diff line change
@@ -295,6 +295,20 @@ they were registered, passing the supplied arguments to each.

Returns `true` if event had listeners, `false` otherwise.

### emitter.eventsList()

Returns an array listing the events for which the emitter has registered
listeners.

```js
const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
console.log(myErr.listEvents());
// Prints ['foo', 'bar']
```

### emitter.getMaxListeners()

Returns the current max listener value for the `EventEmitter` which is either
8 changes: 8 additions & 0 deletions lib/events.js
Original file line number Diff line number Diff line change
@@ -436,6 +436,14 @@ function listenerCount(type) {
return 0;
}

EventEmitter.prototype.listEvents = function() {
const events = this._events;
if (events) {
return Object.getOwnPropertyNames(events).concat(
Object.getOwnPropertySymbols(events));
} else return [];
};

// About 1.5x faster than the two-arg version of Array#splice().
function spliceOne(list, index) {
for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
19 changes: 19 additions & 0 deletions test/parallel/test-events-list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
'use strict';

require('../common');
const EventEmitter = require('events');
const assert = require('assert');

const EE = new EventEmitter();
const m = () => {};
EE.on('foo', () => {});
assert.deepStrictEqual(['foo'], EE.listEvents());
EE.on('bar', m);
assert.deepStrictEqual(['foo', 'bar'], EE.listEvents());
EE.removeListener('bar', m);
assert.deepStrictEqual(['foo'], EE.listEvents());
const s = Symbol('s');
EE.on(s, m);
assert.deepStrictEqual(['foo', s], EE.listEvents());
EE.removeListener(s, m);
assert.deepStrictEqual(['foo'], EE.listEvents());

0 comments on commit e9b1ea9

Please sign in to comment.