I’m implementing an app that makes uses of EventEmitter
. My aim is to use it on both client and server. But strangely, this does not work on server:
Emitter.emit('SomeEvent', {
user,
document,
}
);
I’ve tried importing the event like Emitter = new (require('events').EventEmitter);
I’ve also tried to import a file with
class ClassEmitter extends EventEmitter {}
const Emitter = new ClassEmitter();
My aim it to emit such event after each database query on the server. I am using apollo and graphql.
Any idea on this would be very thankful.
This seems to work ok:
const myEmitter = new (require('events').EventEmitter)()
myEmitter.on('my-event', a => {
console.log('a my-event occurred!', a)
})
myEmitter.emit('my-event')
myEmitter.emit('my-event', {
user: 'mike',
document: 'Empty'
})
The difference is in invoking the function returned by new
Thanks for your replay @mikkelking. importing a file with
import EventEmitter from 'events';
class ClassEmitter extends EventEmitter {}
const Emitter = new ClassEmitter();
export default Emitter;
finally worked. But another problem occurred (or maybe I am the one misunderstanding the nodeJS
event package
): with the above code, event emitted on the server only work on the server and not on the client.
In your example, the myEmitter.on
will only be called on the server, if the event (myEmitter.emit
) was called on the server. The same goes for the client. Am I overlooking something here?