Search code examples
javascriptnode.jselectroneventemitter

Can I use two ioHook event in my electron app?


I'm using the iohook node library for listening to the global mouse and keyboard events.

I actually need two instances of the library for some logic I'm working with. Right now my code look like this

const ioHook = require('iohook');
const ioHook2 = require('iohook');
ioHook.start();
ioHook.on('mouseclick', this.onMouseActivity);
ioHook2.start();
ioHook2.on('mouseclick', this.onMouseActivity2);

Now, After executing executing some logic, I need to stop the first listener. So, I do the following code,

ioHook2.stop();

But, this is stopping all my hooks all together. My expected result is the first ioHook should not be closed and working.

Is this because the event emitters used by both are the same ? like mouseclick,keypress,mousemove etc.. ?

If so, can I remove specific listner specific to the ioHook Instance ?

Thanks for the help. This is bugging me for hours.


Solution

  • There's no first and second but only one hook object. CommonJS modules are evaluated once, so ioHook === ioHook2.

    start starts listening registered hooks and stop stops listening them.

    Since iohook is event emitter, a listener can be unsubscribed as with any other event emitter when needed:

    ioHook.on('mouseclick', onMouseActivity);
    
    ...
    
    ioHook.off('mouseclick', onMouseActivity);