Node.js EventEmitter error

戏子无情 提交于 2019-12-20 05:39:15

问题


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


回答1:


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");


来源:https://stackoverflow.com/questions/14141211/node-js-eventemitter-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!