Skip to content

Commit e87db6c

Browse files
sungpaksmarco-ippolito
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 <[email protected]>
1 parent d69107f commit e87db6c

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

‎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;
@@ -742,9 +746,9 @@ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
742746
*/
743747
EventEmitter.prototype.removeAllListeners=
744748
functionremoveAllListeners(type){
745-
constevents=this._events;
746-
if(events===undefined)
749+
if(!hasEventListener(this))
747750
returnthis;
751+
constevents=this._events;
748752

749753
// Not listening for removeListener, no need to emit
750754
if(events.removeListener===undefined){
@@ -789,14 +793,10 @@ EventEmitter.prototype.removeAllListeners =
789793
};
790794

791795
function_listeners(target,type,unwrap){
792-
constevents=target._events;
793-
794-
if(events===undefined)
796+
if(!hasEventListener(target,type))
795797
return[];
796798

797-
constevlistener=events[type];
798-
if(evlistener===undefined)
799-
return[];
799+
constevlistener=target._events[type];
800800

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

0 commit comments

Comments
(0)