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

events: support event handlers #33646

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
21 changes: 19 additions & 2 deletions lib/internal/event_target.js
Original file line number Diff line number Diff line change
Expand Up @@ -445,10 +445,27 @@ function emitUnhandledRejectionOrErr(that, err, event) {
process.emit('error', err, event);
}

// EventEmitter-ish API:

function defineEventHandler(emitter, name) {
// 8.1.5.1 Event handlers - basically `on[eventName]` attributes
let eventHandlerValue;
Object.defineProperty(emitter, `on${name}`, {
get() {
return eventHandlerValue;
},
set(value) {
if (eventHandlerValue) {
emitter.removeEventListener(name, eventHandlerValue);
}
if (typeof value === 'function') {
emitter.addEventListener(name, value);
}
eventHandlerValue = value;
}
});
}
module.exports = {
Event,
EventTarget,
NodeEventTarget,
defineEventHandler,
};
34 changes: 34 additions & 0 deletions test/parallel/test-eventtarget.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const {
Event,
EventTarget,
NodeEventTarget,
defineEventHandler
} = require('internal/event_target');

const {
Expand Down Expand Up @@ -439,3 +440,36 @@ ok(EventTarget);
const event = new Event('');
strictEqual(event.toString(), '[object Event]');
benjamingr marked this conversation as resolved.
Show resolved Hide resolved
}
{
const target = new EventTarget();
defineEventHandler(target, 'foo');
target.onfoo = common.mustCall();
target.dispatchEvent(new Event('foo'));
}
{
const target = new EventTarget();
defineEventHandler(target, 'foo');
let count = 0;
target.onfoo = () => count++;
target.onfoo = common.mustCall(() => count++);
target.dispatchEvent(new Event('foo'));
strictEqual(count, 1);
}
{
const target = new EventTarget();
defineEventHandler(target, 'foo');
let count = 0;
target.addEventListener('foo', () => count++);
target.onfoo = common.mustCall(() => count++);
target.dispatchEvent(new Event('foo'));
strictEqual(count, 2);
}
{
const target = new EventTarget();
defineEventHandler(target, 'foo');
const fn = common.mustNotCall();
target.onfoo = fn;
strictEqual(target.onfoo, fn);
target.onfoo = null;
target.dispatchEvent(new Event('foo'));
}