I would like to write a constructor function for some work I'm doing in node.js. Amongst other things, I'd like to log the number of instances it creates using an event emitter. At the moment I do this by giving the constructor object a method which is an event emitter. For example:
var EventEmitter = require('events').EventEmitter;
function MyObject() {
...
MyObject.events.emit('createdMyObject')
}
MyObject.events = new EventEmitter();
/* somewhere else... */
MyObject.events.on('createdMyObject', function () {
// Do something when a new instance is created.
});
What I'd really prefer is for the constructor to more directly emit events, so I could listen for them with something like:
MyObject.on('createdMyObject', function () {
// Do something when a new instance is created.
});
Is there a way to do this?
Please note, I don't need the instances to be event emitters (there are lots of examples of this when you google it). I want something equivalent to a class method in the parlance of some other OO languages.