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);
Jelle De Loecker
  • 20,999
  • 27
  • 100
  • 142

1 Answers1

2

It looks like you may be asking for the constructor function itself to be an event emitter. Your code makes the objects produced by new with the constructor. i.e., the object motion produced at the end of your snippet should have an on method (as Vadim Baryshev notes, your code should work as you have it if this is the intent, and if that is the case you can ignore the rest of this answer).

If you really want the constructor to emit events, then take a look at this question and the answer I provided to it. However, it's not a great solution, and there appears to be no way of doing it without using the non-standard __proto__.

A better solution is to make a separate event emitter object for the constructor function to use for emissions. As much as I like the constructor-module pattern, it has to be discarded. Many node modules make the module itself the emitter, and have a function exposed by the module as a constructor. For example:

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');
};

and to instantiate:

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

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

var motionObj = new motion.Motion(app);
Community
  • 1
  • 1
qubyte
  • 17,558
  • 3
  • 30
  • 32