Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you share an EventEmitter in node.js?

Tags:

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?

Thanks!

like image 539
fancy Avatar asked May 18 '12 20:05

fancy


People also ask

How do I emit an event in Node JS?

EventEmitter Class When a new listener is added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired. EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the event and emit is used to fire an event.

How do I add a listener to EventEmitter?

on(event, listener) and eventEmitter. addListener(event, listener) are pretty much similar. It adds the listener at the end of the listener's array for the specified event. Multiple calls to the same event and listener will add the listener multiple times and correspondingly fire multiple times.

What is EventEmitter and how is it used in Node JS?

The EventEmitter is a module that facilitates communication/interaction between objects in Node. EventEmitter is at the core of Node asynchronous event-driven architecture. Many of Node's built-in modules inherit from EventEmitter including prominent frameworks like Express.


2 Answers

@srquinn is correct, you should use a shared single instance:

eventBus.js:

const EventEmitter = require('events'); const emitter = new EventEmitter();  emitter.on('uncaughtException', function (err) {     console.error(err); });  module.exports = emitter; 

Usage:

var bus = require('../path/to/eventBus');  // Register event listener bus.on('eventName', function () {     console.log('triggered!'); });  // Trigger the event somewhere else bus.emit('eventName'); 
like image 93
Lesh_M Avatar answered Oct 10 '22 17:10

Lesh_M


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.

Update:

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.

like image 28
srquinn Avatar answered Oct 10 '22 18:10

srquinn