Matt Stephens Matt Stephens - 5 months ago 31
Node.js Question

Sharing event across modules

For simplicity I have create some small files to test out the idea. Basically i'm looking for a way to emit and event on a module then have that picked up back in the main file for example

This is the main file called to run the app

main.js

var test = require('./test')
var emitter = require('./emitter')
var emit = new emitter()

emit.on('response', function(data) {
console.log(data)
})


This is where the event is fired

fire.js

var emitter = require('./emitter')
var emit = new emitter

var Test = function() {
emit.sendEvent('response', 'test')
}


module.exports = Test


Here is the module created to handle the firing of events for the application

emitter.js

var util = require('util')
var eventEmitter = require('events').EventEmitter

function Event () {
eventEmitter.call(this)
}

util.inherits(Event, eventEmitter)

Event.prototype.sendEvent = function(type, data) {
this.emit(type, data)
}

module.exports = Event


As can be seen in the
emitter.js
I have it setup to be able to emit any custom type including data parsed.

I cannot seem to pick this up in the initial
main.js
file. However if I place
emit.sendEvent('response', 'banana')
in the
main.js
at the bottom of the file it is picked up by the listener above. This would indicate that my
emitter.js
is working correctly.

Any ideas as to why the event emitted in
fire.js
isn't being picked up would be great.

Answer

This is because "emit" object in fire.js and "emit" object in main.js are two completely different objects, so subscribing to events from one will not catch events from another.

What you can do is to export global emitter and use it everywhere. For example:

emitter.js

var util = require('util')
var eventEmitter = require('events').EventEmitter

function Event () {
    eventEmitter.call(this)
}

util.inherits(Event, eventEmitter)

Event.prototype.sendEvent = function(type, data) {
    this.emit(type, data)
}
var eventBus = new Event();
module.exports = {
 emitter : Event,
 eventBus : eventBus
};

This way you can use global event object in all of your modules :

main.js

var test = require('./test')
var emitter = require('./emitter')

emitter.eventBus.on('response', function(data) {
    console.log(data)
})

fire.js

var emitter = require('./emitter')

var Test = function() {
    emitter.eventBus.sendEvent('response', 'test')
}


module.exports = Test