Reputation: 33
I created two modules, "person" and "group", with "group" depending on "person":
person.js:
var events = require('events');
exports.Person = function() {
var personEvents = new events.EventEmitter();
function generateEvent(args) {
console.log("Emitting event with args "+JSON.stringify(args));
personEvents.emit("myEvent", args);
}
return {
personEvents: personEvents,
generateEvent: generateEvent
};
}
group.js:
var PERSON = require("person.js").Person();
var events = require('events');
exports.Group = function() {
function handleEvent(args) {
console.log("Caught event with args "+JSON.stringify(args));
}
PERSON.personEvents.on("myEvent", function(args) {
handleEvent(args);
});
}
Now I have the main program main.js as a separate module:
var PERSON = require("person.js").Person();
var GROUP = require("group.js").Group();
PERSON.generateEvent({ type: "bla" });
When I execute "node ./main.js", I will see the message that the event was generated, but the event is not caught. It seems that the listener in the group module is not bound to the same "personEvents" variable created in the person module in the main namespace.
I am rather new at javascript and its implications for programming. I used examples I found on the internet to get the code I have so far, but I feel that this may not be the correct way to setup the modules and the cross-module events.
Can someone explain to me how I should setup the modules so I can generate events in one module and catch them in another? Thanks!
Upvotes: 2
Views: 5256
Reputation: 42325
When you call var PERSON = require("person.js").Person();
, that creates a new instance. So, when you call it in group.js
, that creates a separate object/instance than the one you create when you call it in main.js
. You could get around this by passing the Person
object to Group
when you create it in main.js
like:
group.js
var events = require('events');
exports.Group = function(PERSON) {
function handleEvent(args) {
console.log("Caught event with args "+JSON.stringify(args));
}
PERSON.personEvents.on("myEvent", function(args) {
handleEvent(args);
});
}
main.js
var PERSON = require("person.js").Person();
var GROUP = require("group.js").Group(PERSON);
PERSON.generateEvent({ type: "bla" });
That being said, that's not a very loosely coupled system. If you want something more loosely coupled, then Group
and Person
should not reference each other at all and the communication between the two should happen in main.js
.
You can accomplish that by changing group.js
and main.js
to something like this:
group.js
var events = require('events');
exports.Group = function() {
function handleEvent(args) {
console.log("Caught event with args "+JSON.stringify(args));
}
}
main.js
var PERSON = require("person.js").Person();
var GROUP = require("group.js").Group();
PERSON.on('myEvent', function(args) {
GROUP.handleEvent(args);
});
PERSON.generateEvent({ type: "bla" });
Upvotes: 4