Search code examples
javascriptnode.jseventemitter

How to have a class constructor emit a event on creating new instances in nodejs


I have a class MyClass:

var MyClass = function(){
  events.EventEmitter.call(this);
  //...
};
util.inherits(MyClass, EventEmitter);

I want it to emit a 'new' event every time a new instance of MyClass is created:

myClassInstance = new MyClass(); // emit a 'new' event from MyClass, not myClassInstance

I want to do this so that I can have an observer to do something every a new instance of MyClass is created. For example:

var MyClass = require('myclass');
MyClass.on('new', function(newInstance) {
  // do something with the new instance of MyClass
};

Is there a way to do it?


Solution

  • You have two options:

    The first way would be to not emit from MyClass and instead make a new EventEmitter instance that would emit instead.

    var MyClassEmitter = new events.EventEmitter();
    var MyClass = function(){
      MyClassEmitter.emit('new', this);
    };
    

    This is the way I would do because it uses the least fanciness and isn't likely to break.

    The second way, working directly with MyClass, you need to mix the EventEmitter behavior onto your constructor.

    var MyClass = function(){
      MyClass.emit('new', this);
    };
    
    // Mix functions directly onto function.
    Object.keys(events.EventEmitter.prototype).forEach(function(prop){
      MyClass[prop] = events.EventEmitter.prototype[prop];
    });
    // Trigger constructor in MyClass context.
    events.EventEmitter.call(MyClass);