diff options
author | James M Snell <jasnell@gmail.com> | 2020-06-22 17:15:54 +0300 |
---|---|---|
committer | James M Snell <jasnell@gmail.com> | 2020-06-24 03:08:13 +0300 |
commit | 4629e96c209bbc6e81a4ff178dcb8afa27feb042 (patch) | |
tree | 4ec5fecbfbda489f14765b7b000312a16b00d0d8 /lib/internal/event_target.js | |
parent | ef91096565830dc6efcdad3ab19aeb685657f9dd (diff) |
events: improve argument handling, start passive
Co-authored-by: Benjamin Gruenbaum <benjamingr@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/34015
Reviewed-By: Denys Otrishko <shishugi@gmail.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Diffstat (limited to 'lib/internal/event_target.js')
-rw-r--r-- | lib/internal/event_target.js | 38 |
1 files changed, 32 insertions, 6 deletions
diff --git a/lib/internal/event_target.js b/lib/internal/event_target.js index 66669b31c96..35d9e7275af 100644 --- a/lib/internal/event_target.js +++ b/lib/internal/event_target.js @@ -203,15 +203,31 @@ class EventTarget { [kRemoveListener](size, type, listener, capture) {} addEventListener(type, listener, options = {}) { - validateListener(listener); - type = String(type); + if (arguments.length < 2) + throw new ERR_MISSING_ARGS('type', 'listener'); + // We validateOptions before the shouldAddListeners check because the spec + // requires us to hit getters. const { once, capture, passive } = validateEventListenerOptions(options); + if (!shouldAddListener(listener)) { + // The DOM silently allows passing undefined as a second argument + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + const w = new Error(`addEventListener called with ${listener}` + + ' which has no effect.'); + w.name = 'AddEventListenerArgumentTypeWarning'; + w.target = this; + w.type = type; + process.emitWarning(w); + return; + } + type = String(type); + let root = this[kEvents].get(type); if (root === undefined) { @@ -242,9 +258,15 @@ class EventTarget { } removeEventListener(type, listener, options = {}) { - validateListener(listener); + if (!shouldAddListener(listener)) + return; + type = String(type); - const { capture } = validateEventListenerOptions(options); + // TODO(@jasnell): If it's determined this cannot be backported + // to 12.x, then this can be simplified to: + // const capture = Boolean(options?.capture); + const capture = options != null && options.capture === true; + const root = this[kEvents].get(type); if (root === undefined || root.next === undefined) return; @@ -426,13 +448,17 @@ Object.defineProperties(NodeEventTarget.prototype, { // EventTarget API -function validateListener(listener) { +function shouldAddListener(listener) { if (typeof listener === 'function' || (listener != null && typeof listener === 'object' && typeof listener.handleEvent === 'function')) { - return; + return true; } + + if (listener == null) + return false; + throw new ERR_INVALID_ARG_TYPE('listener', 'EventListener', listener); } |