Listen to All Emitted Events in Node.js

后端 未结 12 1316
孤街浪徒
孤街浪徒 2020-12-24 00:06

In Node.js is there any way to listen to all events emitted by an EventEmitter object?

e.g., can you do something like...

event_emitter.on(\         


        
12条回答
  •  悲&欢浪女
    2020-12-24 00:33

    Ran into the same problem today, heres a solution:

    Object.create(Object.assign({},EventEmitter.prototype, {
      _onAnyListeners:[],
      emit:function(...args){
        //Emit event on every other server
    
        if(this._fireOnAny && typeof this._fireOnAny === 'function'){
          this._fireOnAny.apply(this,args)
        }
    
        EventEmitter.prototype.emit.apply(this,args)
      },
      _fireOnAny:function(...args){
        this._onAnyListeners.forEach((listener)=>listener.apply(this,args))
      },
      onAny:function(func){
        if(typeof func !== 'function'){
          throw new Error('Invalid type');
        }
        this._onAnyListeners.push(func);
      },
      removeOnAny:function(func){
        const index = this._onAnyListeners.indexOf(func);
        if(index === -1){
          return;
        }
        this._onAnyListeners.splice(index,1);
      }
    }));
    

提交回复
热议问题