Search code examples
node.jsinheritanceeventemitterchangelog

node.js v0.12.x changes in EventEmitter ruins inheritance


There is some changes in node.js 0.12.x related to events module. This changes makes my code that extends EventEmitter class non-workable. Here is code that works fine in node.js v0.10.35: teh_emitter.js:

var EventEmitter = require('events');
var util = require('util');

util.inherits(TehEmitter, EventEmitter);


function TehEmitter(){

	EventEmitter.call(this);
}


TehEmitter.prototype.on('start', function (fCallback) {

	fCallback();
});

module.exports = TehEmitter;

test_teh_emitter.js:

var TehEmitter =  require('./teh_emitter');

describe('EventEmitter tests', function(){

	describe('#emit() function', function(){

		it('should fire start event', function(fCallback){

			var oEmitter = new TehEmitter(fCallback);

			oEmitter.emit('start', fCallback);

		});
	})
});

But on node.js v0.12.7 it says: 0 passing (2s) 1 failing

1) EventEmitter tests #emit() function should fire start event:
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

I know that in 0.12.x one should assign: var EventEmitter = require('events'); (though require('events').EventEmitter; should still work for backwards compatability). But it doesn't helps.

How am I gonna fix this problem?


Solution

  • This was changed in 2c6b424 because of a bug involving event handlers bleeding into all other instances of the same object/"class" (see 7157).

    Probably your best bet for compatibility is to just add the event handler in the constructor:

    function TehEmitter(){
      EventEmitter.call(this);
      this.on('start', onStart);
    }
    
    function onStart(fCallback) {
      fCallback();
    }