0

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?

Community
  • 1
  • 1
gochomugo
  • 25
  • 6

1 Answers1

2

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);
treeno
  • 2,510
  • 1
  • 20
  • 36
  • It would be helpful to follow that up with a sample code on how to do that – gochomugo Aug 24 '14 at 00:57
  • I have added an example. There is even an design-principle that says something like "delegaton is better then inheritence". I don't always agree with that, however I think it is much better then multiple inheritence as you would have it here. – treeno Aug 24 '14 at 16:48
  • Will I have to write methods like push and map that delegate to the Array? Isn't that tiring? – gochomugo Aug 25 '14 at 16:05
  • Yes, that is why I don't always agree with that principle ;-). But this seems to be the best option to me, since there is no multiple inheritance and changing the parent-prototype of Array would apply globally (change all Arrays). – treeno Aug 26 '14 at 09:36
  • This solved my problem although it requires time-to-time update for method delegations. I accept this answer. :-) – gochomugo Jan 06 '15 at 17:11