Search code examples
javascriptnode.jseventemitter

Node.js - Listen for when listeners are registered


In Node.js, we have the standard event emitter:

const EE = require('events');

const ee = new EE();

ee.on('x', function(){

});

what I would like to do, is listen for when a client registers a listener. The purpose is so that if the emitter is in a particular state, it will take actions upon registration.

To be clear, when ee.on() is called, for a particular event 'x', I want to take some actions.

How can I do this without monkey-patching all event emitters in Node.js?

If I do the following, am I patching the prototype method or the instance method?

let on = ee.on;

ee.on = function(){
    if(ee.y === true){
      process.next(function(){
        ee.emit('done');
      });
    }
    return on.apply(ee, arguments);
};

this is of course the same as:

   let on = ee.on;

    ee.on = function(){
        if(this.y === true){
          process.next(() => {
            this.emit('done');
          });
        }
       return on.apply(this, arguments);
    };

I think this will work, but I am not sure. I think this will only effect this one particular event emitter, not all event emitters, because it will not change the prototype...


Solution

  • To have the same behavior replicated you should create a new class/prototype from where all other instances will inherit.

    EDIT:

    <file_my_class.js>:
    var   Util = require('util');
    const EventEmmiter = require('events');
    
    // private data goes here
    ...
    
    // public data follows
    module.exports = MyClass;
    
    function MyClass() {
    ...
    }
    
    Util.inherits (MyClass, EventEmmiter);
    
    MyClass.prototype.mymethod = function () {
        someobj.on('somevent', () => {
            ...
            if (test_condition_ok) {
               this.emit ('myeventname');
            }
        });
    }
    
    <main.js>:
    
    var MyClass = require('./file_my_class.js');
    var myclass_instance = new MyClass();
    
    myclass_instance.mymethod();
    
    myclass_instance.on('myeventname', () => {
          // Do Something
       });