0

I'm trying to add the event listener to my class, but it fails, telling me the object has no 'on' method.

Here's the class in its own file:

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

var Motion = function Motion (app) {

    events.EventEmitter.call(this);

    // Load models
    app.loadModel('motion', 'motion');

    this.on('testevent', function () {
        console.log('an event has happened');
    });

    this.emit('testevent');

}

util.inherits(Motion, events.EventEmitter);

module.exports = Motion;

And here's how I instantiate it:

var Motion = require('./plugins/motion.js');
var motion = new Motion(app);
4

1 回答 1

2

看起来您可能要求构造函数本身成为事件发射器。您的代码new使用构造函数生成对象。即,在motion您的代码段末尾生成的对象应该有一个on方法(正如 Vadim Baryshev 所指出的,如果这是意图,您的代码应该按照您的意愿工作,如果是这种情况,您可以忽略此答案的其余部分) .

如果你真的希望构造函数发出事件,那么看看这个问题和我提供给它的答案。但是,这不是一个很好的解决方案,而且如果不使用非标准的__proto__.

更好的解决方案是为构造函数创建一个单独的事件发射器对象以用于发射。尽管我很喜欢构造函数模块模式,但它必须被丢弃。许多节点模块使模块本身成为发射器,并具有由模块公开的函数作为构造函数。例如:

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

exports = module.exports = new events.EventEmitter();

exports.Motion = function (app) {
    // Load models
    app.loadModel('motion', 'motion');

    // Emit event
    exports.emit('testevent');
};

并实例化:

var motion = require('./plugins/motion');

motion.on('testevent', function () {
    console.log('an object was constructed');
});

var motionObj = new motion.Motion(app);
于 2012-12-30T18:18:05.910 回答