Skip to content

Commit

Permalink
events: support dispatching event from event
Browse files Browse the repository at this point in the history
Co-authored-by: Benjamin Gruenbaum <benjamingr@gmail.com>

PR-URL: #34015
Reviewed-By: Denys Otrishko <shishugi@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
  • Loading branch information
jasnell authored and codebytere committed Jun 27, 2020
1 parent 5ce1533 commit ea1a2d7
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 15 deletions.
14 changes: 3 additions & 11 deletions lib/internal/event_target.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ const {
Map,
NumberIsInteger,
Object,
Set,
Symbol,
SymbolFor,
SymbolToStringTag,
Expand Down Expand Up @@ -199,7 +198,6 @@ class EventTarget {
static [kIsEventTarget] = true;

[kEvents] = new Map();
#emitting = new Set();

[kNewListener](size, type, listener, once, capture, passive) {}
[kRemoveListener](size, type, listener, capture) {}
Expand Down Expand Up @@ -266,25 +264,20 @@ class EventTarget {
}

dispatchEvent(event) {
if (!(event instanceof Event)) {
if (!(event instanceof Event))
throw new ERR_INVALID_ARG_TYPE('event', 'Event', event);
}

if (!isEventTarget(this)) {
if (!isEventTarget(this))
throw new ERR_INVALID_THIS('EventTarget');
}

if (this.#emitting.has(event.type) ||
event[kTarget] !== null) {
if (event[kTarget] !== null)
throw new ERR_EVENT_RECURSION(event.type);
}

const root = this[kEvents].get(event.type);
if (root === undefined || root.next === undefined)
return true;

event[kTarget] = this;
this.#emitting.add(event.type);

let handler = root.next;
let next;
Expand All @@ -310,7 +303,6 @@ class EventTarget {
handler = next;
}

this.#emitting.delete(event.type);
event[kTarget] = undefined;

return event.defaultPrevented !== true;
Expand Down
7 changes: 3 additions & 4 deletions test/parallel/test-eventtarget.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,13 +293,12 @@ ok(EventTarget);

// Once handler only invoked once
const ev = common.mustCall((event) => {
throws(() => eventTarget.dispatchEvent(new Event('foo')), {
code: 'ERR_EVENT_RECURSION'
});
// Can invoke the same event name recursively
eventTarget.dispatchEvent(new Event('foo'));
});

// Errors in a handler won't stop calling the others.
eventTarget.addEventListener('foo', ev);
eventTarget.addEventListener('foo', ev, { once: true });

eventTarget.dispatchEvent(new Event('foo'));
}
Expand Down

0 comments on commit ea1a2d7

Please sign in to comment.