Skip to content

events: support EventTarget in once #27977

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

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
12 changes: 11 additions & 1 deletion lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,16 @@ function once(emitter, name) {
emitter.once('error', errorListener);
}

emitter.once(name, eventListener);
if (typeof emitter.once === 'function' && typeof emitter.removeListener === 'function') {
return emitter.once(name, eventListener);
}
if (typeof emitter.addEventListener === 'function') {
return new Promise((resolve) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Extra Promise not needed here?

// Although EventTarget does not have `error` event semantics like Node
// EventEmitters, we do not listen to `error` events here.
emitter.addEventListener(name, resolve, { once: true });
});
}
throw new ERR_INVALID_ARG_TYPE('emitter', 'EventEmitter', emitter);
});
}
21 changes: 20 additions & 1 deletion test/parallel/test-events-once.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,29 @@ async function onceError() {
strictEqual(ee.listenerCount('myevent'), 0);
}

async function onceWithEventTarget() {
var emitter = new class EventTargetLike extends EventEmitter {
addEventListener(name, listener, options) {
if (options.once) {
this.once(name, listener);
} else {
this.on(name, listener);
}
}
};
Copy link
Contributor

@apapirovski apapirovski May 31, 2019

Choose a reason for hiding this comment

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

Add emitter.removeListener = undefined; to hit the right code path in this test?

process.nextTick(() => {
emitter.emit('myevent', 42);
});
const [value] = await once(emitter, 'myevent');
Copy link
Member

Choose a reason for hiding this comment

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

Also check that there are no interesting error semantics?

strictEqual(value, 42);
strictEqual(emitter.listenerCount('myevent'), 0);
}

Promise.all([
onceAnEvent(),
onceAnEventWithTwoArgs(),
catchesErrors(),
stopListeningAfterCatchingError(),
onceError()
onceError(),
onceWithEventTarget()
]).then(common.mustCall());