简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM