Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding multiple listeners at once #15787

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -525,3 +525,11 @@ function unwrapListeners(arr) {
}
return ret;
}

EventEmitter.prototype.onMultiple = function onMultiple(eventList, handler) {

for(let i = 0; i < eventList.length; i++) {
this.on(eventList[i], handler);
}

};
24 changes: 24 additions & 0 deletions test/parallel/test-event-emitter-onMultiple.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict';
const common = require('../common');

// This test ensures that it is possible to add a listener to multiple events at once

const assert = require('assert');
const EventEmitter = require('../../lib/events');
const myEE = new EventEmitter();

async function main() {

// Input
const inputArray = ["a", "b", Symbol('symbol')];
const emptyFunction = function() {};

// Test
await myEE.onMultiple(inputArray, emptyFunction);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this awaited? I'm also not sure this actually tests the feature itself.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this awaited?

Good point. I'll fix it. Thanks.

I'm also not sure this actually tests the feature itself.

To me, it seems like you're not conviced that using .eventNames() isn't the proper way to test the code. I mean, I could agree on some degree. How do you propose to change it?

const outputArray = await myEE.eventNames();

// Assert
await assert.deepStrictEqual(inputArray, outputArray, "The listener did not get binded to multiple events");
}

main()