How to make an EventEmitter listen to another EventEmitter in Node.js?

家住魔仙堡 提交于 2019-12-05 14:29:21

Note that EventEmitters are kind of sole-source in javascript. They are not system-wide events that everyone can listen to. They are objects that can emit events to support the asynchronous patterns. To accomplish what you want, you need multiple things listening to the same emitter. Something like this:

'use strict';
var events = require( 'events' );
//Create a new sole-source event emitter
var emitterA = new events.EventEmitter();

//create a container that can listen
function EventListener( name ) {
  console.log( 'new event listener, name=' + name );
  this.name = name;
  this.ack = function() {
    console.log( this.name + ' just heard testA' );
  };
  this.listenTo = function( event, emitter ) {
    var self = this;
    emitter.on( event, function() {
      self.ack();
    } );
  };
}

var listenerA = new EventListener( 'A', emitterA );
listenerA.listenTo( 'testA', emitterA );

var listenerB = new EventListener( 'B', emitterA );
listenerB.listenTo( 'testA', emitterA );

setInterval( function() {
  emitterA.emit( 'testA' );
}, 1000 );

Outputs:

$ node testfile.js 
new event listener, name=A
new event listener, name=B
A just heard testA
B just heard testA
A just heard testA
B just heard testA
...

Note that for your additional use cases, you will want to use WebSockets. EventEmitters will not work the way you want them to, especially to remote clients. (The comment for socket.io is indeed a good place to start.)

You can try to emit the event forward to the element emitterB:

emitterA.addListener("testA", function(){
    console.log("emitterA detected testA");

    // When everything is done emit the event to emitterB
    emitterB.emit('testA');
});

Or if there are multiple events to emit forward you can create something like a event bubbling:

function bubbleEvents(from, to) {

    var oldEmit = from.emit;

    from.emit = function (event) {

        var args = Array.prototype.slice.call(arguments, 1),
            newArgs = [event].concat(args);

        oldEmit.apply(from, newArgs);
        to.emit.apply(to, newArgs);
    };
}

// and call it
bubbleEvents(emitterA, emitterB);

P.S. It is not a good practice to edit the methods of an object like this, but for some dirty purposes it can serve very well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!