Skip to content

Commit

Permalink
events: support event handlers
Browse files Browse the repository at this point in the history
PR-URL: #34015
Reviewed-By: Denys Otrishko <[email protected]>
Reviewed-By: Benjamin Gruenbaum <[email protected]>
  • Loading branch information
benjamingr authored and codebytere committed Jun 27, 2020
1 parent b392fdd commit 91b6c09
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
21 changes: 19 additions & 2 deletions lib/internal/event_target.js
Original file line number Diff line number Diff line change
Expand Up @@ -479,10 +479,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 @@ -438,6 +439,39 @@ ok(EventTarget);
const event = new Event('');
strictEqual(event.toString(), '[object Event]');
}
{
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'));
}

{
// `this` value of dispatchEvent
Expand Down

0 comments on commit 91b6c09

Please sign in to comment.