Am currently working on a project where I require to inherit from EventEmitter. I need an array to emit events on certain cases, say, when some length has been exceeded.
I used this snippet:
var events = require('events');
Array.prototype.__proto__ = events.EventEmitter.prototype;
It works fine, but it is said it is anti-pattern.
In another question, it is suggested to use:
util.inherits(Array, events.EventEmitter.prototype);
But it does NOT work. So what is the right way to do this?
The problem here is, that this will change all Arrays in your application and not only one. In this situation it would be better to use a new Type that extends from EventEmitter and delegates to an Array.
i.e.
// Create a new object that ...
function MyEventArray() {
// ...owns an Array as property...
this.array = new Array();
}
// ... and extends from EventEmitter...
MyEventArray.prototype = Object.create(EventEmitter.prototype);
MyEventArray.prototype.constructor = MyEventArray;
// ... and has functions that delegate to the array.
MyEventArray.prototype.push(obj) {
this.array.push(obj);
}
...
// This object is an EventEmitter and can be used like an Array:
var myArray = new MyEventArray();
myArray.push(someStuff);