Skip to content

Commit a2c8de7

Browse files
sungpaksruyadorno
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 27b0236 commit a2c8de7

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
@@ -287,6 +287,12 @@ ObjectDefineProperty(EventEmitter, 'defaultMaxListeners', {
287287
},
288288
});
289289

290+
functionhasEventListener(self,type){
291+
if(type===undefined)
292+
returnself._events!==undefined;
293+
returnself._events!==undefined&&self._events[type]!==undefined;
294+
};
295+
290296
ObjectDefineProperties(EventEmitter,{
291297
kMaxEventTargetListeners: {
292298
__proto__: null,
@@ -680,13 +686,11 @@ EventEmitter.prototype.removeListener =
680686
functionremoveListener(type,listener){
681687
checkListener(listener);
682688

683-
constevents=this._events;
684-
if(events===undefined)
689+
if(!hasEventListener(this,type))
685690
returnthis;
686691

692+
constevents=this._events;
687693
constlist=events[type];
688-
if(list===undefined)
689-
returnthis;
690694

691695
if(list===listener||list.listener===listener){
692696
this._eventsCount-=1;
@@ -740,9 +744,9 @@ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
740744
*/
741745
EventEmitter.prototype.removeAllListeners=
742746
functionremoveAllListeners(type){
743-
constevents=this._events;
744-
if(events===undefined)
747+
if(!hasEventListener(this))
745748
returnthis;
749+
constevents=this._events;
746750

747751
// Not listening for removeListener, no need to emit
748752
if(events.removeListener===undefined){
@@ -787,14 +791,10 @@ EventEmitter.prototype.removeAllListeners =
787791
};
788792

789793
function_listeners(target,type,unwrap){
790-
constevents=target._events;
791-
792-
if(events===undefined)
794+
if(!hasEventListener(target,type))
793795
return[];
794796

795-
constevlistener=events[type];
796-
if(evlistener===undefined)
797-
return[];
797+
constevlistener=target._events[type];
798798

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

0 commit comments

Comments
 (0)