Skip to content

Commit bdb6d12

Browse files
sungpaksaduh95
authored andcommitted
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: #55230 Reviewed-By: Jason Zhang <xzha4350@gmail.com>
1 parent 787e51e commit bdb6d12

1 file changed

Lines changed: 12 additions & 12 deletions

File tree

‎lib/events.js‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,12 @@ ObjectDefineProperty(EventEmitter, 'defaultMaxListeners', {
276276
},
277277
});
278278

279+
functionhasEventListener(self,type){
280+
if(type===undefined)
281+
returnself._events!==undefined;
282+
returnself._events!==undefined&&self._events[type]!==undefined;
283+
};
284+
279285
ObjectDefineProperties(EventEmitter,{
280286
kMaxEventTargetListeners: {
281287
__proto__: null,
@@ -669,13 +675,11 @@ EventEmitter.prototype.removeListener =
669675
functionremoveListener(type,listener){
670676
checkListener(listener);
671677

672-
constevents=this._events;
673-
if(events===undefined)
678+
if(!hasEventListener(this,type))
674679
returnthis;
675680

681+
constevents=this._events;
676682
constlist=events[type];
677-
if(list===undefined)
678-
returnthis;
679683

680684
if(list===listener||list.listener===listener){
681685
this._eventsCount-=1;
@@ -729,9 +733,9 @@ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
729733
*/
730734
EventEmitter.prototype.removeAllListeners=
731735
functionremoveAllListeners(type){
732-
constevents=this._events;
733-
if(events===undefined)
736+
if(!hasEventListener(this))
734737
returnthis;
738+
constevents=this._events;
735739

736740
// Not listening for removeListener, no need to emit
737741
if(events.removeListener===undefined){
@@ -776,14 +780,10 @@ EventEmitter.prototype.removeAllListeners =
776780
};
777781

778782
function_listeners(target,type,unwrap){
779-
constevents=target._events;
780-
781-
if(events===undefined)
783+
if(!hasEventListener(target,type))
782784
return[];
783785

784-
constevlistener=events[type];
785-
if(evlistener===undefined)
786-
return[];
786+
constevlistener=target._events[type];
787787

788788
if(typeofevlistener==='function')
789789
returnunwrap ? [evlistener.listener||evlistener] : [evlistener];

0 commit comments

Comments
 (0)