jtomasrl
jtomasrl

Reputation: 1451

Node.js EventEmitter error

I have an error when trying to inherit EvenEmitter

/* Consumer.js */
var EventEmitter = require('events').EventEmitter;
var util = require('util');

var Consumer = function() {};

Consumer.prototype = {
  // ... functions ...
  findById: function(id) {
    this.emit('done', this);
  }
};

util.inherits(Consumer, EventEmitter);
module.exports = Consumer;

/* index.js */
var consumer = new Consumer();
consumer.on('done', function(result) {
  console.log(result);
}).findById("50ac3d1281abba5454000001");

/* ERROR CODE */
{"code":"InternalError","message":"Object [object Object] has no method 'findById'"}

I've tried almost everything and still dont work

Upvotes: 0

Views: 1414

Answers (1)

Hector Correa
Hector Correa

Reputation: 26690

A couple of things. You are overwriting the prototype rather than extending it. Also, move the util.inherits() call before you add the new method:

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

var Consumer = function Consumer() {}

util.inherits(Consumer, EventEmitter);

Consumer.prototype.findById = function(id) {
    this.emit('done', this);
    console.log('found');
};

var c = new Consumer();
c.on('done', function(result) {
  console.log(result);
});

c.findById("50ac3d1281abba5454000001");

Upvotes: 3

Related Questions