Mark
Mark

Reputation: 69920

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?

Upvotes: 2

Views: 4187

Answers (1)

jmar777
jmar777

Reputation: 39649

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

Upvotes: 3

Related Questions