The way event emitter works is that you have to use the same event emitter object to listen on that you used to emit. So you need something like this:
To share this among different parts of your project you should create a module out of it and require it wherever needed.
my-event.js:
var eventEmitter = new require('events').EventEmitter();
module.exports = eventEmitter;
Then you require
this eventEmitter
wherever you want to use it
blog.js:
var myEvent = require('../my-event');
blog.post('save',function(blog){
myEvent.emit('newBlog', blog);
});
app.js:
var myEvent = require('./my-event');
myEvent.on('newBlog', console.log);
If you don't want to go through the trouble of creating and requiring your own module, you can use the global process
which is also an EventEmitter.
anywhere:
process.on('my-custom-event', myCustomHandler);
anywhere-else:
process.emit('my-custom-event', data);
Although a fair warning: you're polluting the global scope. If some other module is also doing the same and using the same event names then you have a conflict which may surface in unexpected manner and be even harder to debug.
this.emit('newBlog',blog)
instead ofeventEmitter.emit('newBlog',blog);
,but the event listener won't work. and I think if I have to pass the same event emitter whenever i need to use it , then what is the point? I can just replace event with actual business logic to save me a bunch of trouble. – Headman