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!
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.
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.
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.
@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');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With