fancy fancy - 1 year ago 106
Javascript Question

How do you share an EventEmitter in node.js?

I want to emit events from one file/module/script and listen to them in another file/module/script. How can I share the emitter variable between them without polluting the global namespace?


Answer Source

You can pass arguments to require calls thusly:

var myModule = require('myModule')(Events)

And then in "myModule"

module.exports = function(Events) {
    // Set up Event listeners here

With that said, if you want to share an event emitter, create an emitter object and then pass to your "file/module/script" in a require call.


Though correct, this is a code smell as you are now tightly coupling the modules together. Instead, consider using a centralized event bus that can be required into each module.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download