mirror of
https://github.com/nodejs/node.git
synced 2024-11-21 13:09:21 +01:00
events: add hasEventListener util for validate
There was some repetitive logics that validated the existence of eventlisteners. We now replace this with a single line of, `hasEventListener(self, type)`. `self` is the object(e.g. EventEmitter) to be checked whether eventlisteners exists or not. `type` is the type of eventlisteners, which can be `undefined` PR-URL: https://github.com/nodejs/node/pull/55230 Reviewed-By: Jason Zhang <xzha4350@gmail.com>
This commit is contained in:
parent
d9540b51eb
commit
7a461edbbb
@ -276,6 +276,12 @@ ObjectDefineProperty(EventEmitter, 'defaultMaxListeners', {
|
||||
},
|
||||
});
|
||||
|
||||
function hasEventListener(self, type) {
|
||||
if (type === undefined)
|
||||
return self._events !== undefined;
|
||||
return self._events !== undefined && self._events[type] !== undefined;
|
||||
};
|
||||
|
||||
ObjectDefineProperties(EventEmitter, {
|
||||
kMaxEventTargetListeners: {
|
||||
__proto__: null,
|
||||
@ -669,13 +675,11 @@ EventEmitter.prototype.removeListener =
|
||||
function removeListener(type, listener) {
|
||||
checkListener(listener);
|
||||
|
||||
const events = this._events;
|
||||
if (events === undefined)
|
||||
if (!hasEventListener(this, type))
|
||||
return this;
|
||||
|
||||
const events = this._events;
|
||||
const list = events[type];
|
||||
if (list === undefined)
|
||||
return this;
|
||||
|
||||
if (list === listener || list.listener === listener) {
|
||||
this._eventsCount -= 1;
|
||||
@ -729,9 +733,9 @@ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
|
||||
*/
|
||||
EventEmitter.prototype.removeAllListeners =
|
||||
function removeAllListeners(type) {
|
||||
const events = this._events;
|
||||
if (events === undefined)
|
||||
if (!hasEventListener(this))
|
||||
return this;
|
||||
const events = this._events;
|
||||
|
||||
// Not listening for removeListener, no need to emit
|
||||
if (events.removeListener === undefined) {
|
||||
@ -776,14 +780,10 @@ EventEmitter.prototype.removeAllListeners =
|
||||
};
|
||||
|
||||
function _listeners(target, type, unwrap) {
|
||||
const events = target._events;
|
||||
|
||||
if (events === undefined)
|
||||
if (!hasEventListener(target, type))
|
||||
return [];
|
||||
|
||||
const evlistener = events[type];
|
||||
if (evlistener === undefined)
|
||||
return [];
|
||||
const evlistener = target._events[type];
|
||||
|
||||
if (typeof evlistener === 'function')
|
||||
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
|
||||
|
Loading…
Reference in New Issue
Block a user