Skip to content

Commit

Permalink
events: add hasEventListener util for validate
Browse files Browse the repository at this point in the history
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`
  • Loading branch information
chosunghoon committed Oct 2, 2024
1 parent dec1099 commit 4befc9e
Showing 1 changed file with 14 additions and 14 deletions.
28 changes: 14 additions & 14 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,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,
Expand Down Expand Up @@ -667,14 +673,12 @@ EventEmitter.prototype.prependOnceListener =
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
checkListener(listener);

const events = this._events;
if (events === undefined)

Check failure on line 676 in lib/events.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Trailing spaces not allowed
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;
Expand Down Expand Up @@ -728,9 +732,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) {
Expand Down Expand Up @@ -775,14 +779,10 @@ EventEmitter.prototype.removeAllListeners =
};

function _listeners(target, type, unwrap) {
const events = target._events;

if (events === undefined)
return [];

const evlistener = events[type];
if (evlistener === undefined)
if (!hasEventListener(target, type))
return [];

Check failure on line 784 in lib/events.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Trailing spaces not allowed
const evlistener = target._events[type];

if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
Expand Down

0 comments on commit 4befc9e

Please sign in to comment.