From dd89cfeb30c6ae9035cf5bf5f18e6ac1a9e20f0d Mon Sep 17 00:00:00 2001 From: ZYSzys <17367077526@163.com> Date: Sun, 11 Nov 2018 19:31:22 +0800 Subject: [PATCH] events: extract listener check as a function PR-URL: https://github.com/nodejs/node/pull/24303 Reviewed-By: Anna Henningsen Reviewed-By: Ruben Bridgewater Reviewed-By: Denys Otrishko Reviewed-By: Franziska Hinkelmann Reviewed-By: James M Snell --- lib/events.js | 29 +++++++++++++---------------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/lib/events.js b/lib/events.js index e59ff3f04dd93b..5dfa34469b09af 100644 --- a/lib/events.js +++ b/lib/events.js @@ -48,6 +48,13 @@ function lazyErrors() { return errors; } +function checkListener(listener) { + if (typeof listener !== 'function') { + const errors = lazyErrors(); + throw new errors.ERR_INVALID_ARG_TYPE('listener', 'Function', listener); + } +} + Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { @@ -195,10 +202,7 @@ function _addListener(target, type, listener, prepend) { var events; var existing; - if (typeof listener !== 'function') { - const errors = lazyErrors(); - throw new errors.ERR_INVALID_ARG_TYPE('listener', 'Function', listener); - } + checkListener(listener); events = target._events; if (events === undefined) { @@ -283,20 +287,16 @@ function _onceWrap(target, type, listener) { } EventEmitter.prototype.once = function once(type, listener) { - if (typeof listener !== 'function') { - const errors = lazyErrors(); - throw new errors.ERR_INVALID_ARG_TYPE('listener', 'Function', listener); - } + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { - if (typeof listener !== 'function') { - const errors = lazyErrors(); - throw new errors.ERR_INVALID_ARG_TYPE('listener', 'Function', listener); - } + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); return this; }; @@ -306,10 +306,7 @@ EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; - if (typeof listener !== 'function') { - const errors = lazyErrors(); - throw new errors.ERR_INVALID_ARG_TYPE('listener', 'Function', listener); - } + checkListener(listener); events = this._events; if (events === undefined)