Search code examples
node.jsasynchronousmoduleeventemitter

node.js - Emit events from an object


I have the following module in node.js:

var obj = {};
obj.prop1 = "value1";
obj.prop2 = "value2";

asyncFunction(function(data) {
     obj.prop3 = data;
     // I would like to do: obj.emit("completed");
});

module.exports = obj;

So I can import it like:

var imp = require('./obj');

imp.on("completed", function() {
     console.log("Hello!");
});

How can I do it?


Solution

  • You will need to make obj an EventEmitter. This can be done pretty simply - just change this:

    var obj = {};
    

    To this:

    var EventEmitter = require('events').EventEmitter;
    var obj = new EventEmitter();