Skip to content

Commit

Permalink
events: add eventNames() method
Browse files Browse the repository at this point in the history
Per #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 `eventNames()` method that
returns an array of the events with currently registered listeners.

PR-URL: #5617
Reviewed-By: Brian White <mscdex@mscdex.net>
Reviewed-By: Сковорода Никита Андреевич <chalkerx@gmail.com>
Reviewed-By: Sakthipriyan Vairamani <thechargingvolcano@gmail.com>
  • Loading branch information
jasnell committed Mar 15, 2016
1 parent f380db2 commit b6e3fa7
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
18 changes: 18 additions & 0 deletions doc/api/events.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,24 @@ they were registered, passing the supplied arguments to each.

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

### emitter.eventNames()

Returns an array listing the events for which the emitter has registered
listeners. The values in the array will be strings or Symbols.

```js
const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});

const sym = Symbol('symbol');
myEE.on(sym, () => {});

console.log(myErr.eventNames());
// Prints ['foo', 'bar', Symbol('symbol')]
```

### emitter.getMaxListeners()

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

EventEmitter.prototype.eventNames = function eventNames() {
if (this._eventsCount > 0) {
const events = this._events;
return Object.keys(events).concat(
Object.getOwnPropertySymbols(events));
}
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)
Expand Down
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.eventNames());
EE.on('bar', m);
assert.deepStrictEqual(['foo', 'bar'], EE.eventNames());
EE.removeListener('bar', m);
assert.deepStrictEqual(['foo'], EE.eventNames());
const s = Symbol('s');
EE.on(s, m);
assert.deepStrictEqual(['foo', s], EE.eventNames());
EE.removeListener(s, m);
assert.deepStrictEqual(['foo'], EE.eventNames());

0 comments on commit b6e3fa7

Please sign in to comment.