TypeError:对象函数EventEmitter()

时间:2014-02-03 12:07:23

标签: javascript node.js events

我有Node.js EventEmitter错误。当我运行我的脚本时,我收到此错误。脚本处于回溯状态。它是计费对象(它必须在MongoDB中更新货币价值)。

C:\node\billing\node_modules\models\ticket.js:20
emitter.on('new_bill', function(){
    ^
TypeError: Object function EventEmitter() {
  this.domain = null;
  if (exports.usingDomains) {
    // if there is an active domain, then attach to it.
    domain = domain || require('domain');
    if (domain.active && !(this instanceof domain.Domain)) {
      this.domain = domain.active;
    }
  }
  this._events = this._events || {};
  this._maxListeners = this._maxListeners || defaultMaxListeners;
  } has no method 'on'
  at Object.<anonymous> (C:\node\billing\node_modules\models\ticket.js:20:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (C:\node\billing\node_modules\routes\pay.js:1:76)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
DEBUG: Program node app exited with code 8

这是我的剧本:

var emitter = require('events').EventEmitter;
var log4js = require('log4js');
var log = log4js.getLogger();
var redis = require("redis"),
   client = redis.createClient();
var HttpError = require('error').HttpError;
var User = require("models/user").User;


function ticket(req, res, next, code, amount){
   this.req = req;
   this.res = res;
   this.next = next;
   this.code = code;
   this.amount = amount;
}

emitter.prototype = ticket;

emitter.on('new_bill', function(){
   client.set(this.code, this.amount);
});


emitter.on('bill_closed', function(){
   client.get(this.code, function (err, amount) {
        if(err) var err = new HttpError(500, "Redis connection failed");
        log.error(err);
        this.next(err);
        User.upMoney(this.req.session.user._id, amount, function(err){
            if(err) var err = new HttpError(500, "Redis connection failed");
            log.error(err);
            this.next(err);
        });
    });
 });


exports.module = emitter;

这里,我使用节点js与v0.10.25。 我没有找到任何方法来解决谷歌这个问题。 任何人都可以帮忙解决这个问题吗?

2 个答案:

答案 0 :(得分:3)

EventEmitter应该使用new进行实例化。

var Emitter = require('events').EventEmitter,
    emitter = new Emitter();

http://nodejs.org/api/events.html

答案 1 :(得分:0)

您没有以正确的方式创建对象 你应该使用继承:

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

function Ticket(req, res, next, code, amount){
  EventEmitter.call(this);
  this.req = req;
  this.res = res;
  this.next = next;
  this.code = code;
  this.amount = amount;
}

util.inherits(Ticket, EventEmitter);

var ticket = module.exports = new Ticket();

ticket.on('new_bill', function () { /* ... */ });
ticket.on('bill_closed', function () { /* ... */ });