Listen to All Emitted Events in Node.js

后端 未结 12 1298
孤街浪徒
孤街浪徒 2020-12-24 00:06

In Node.js is there any way to listen to all events emitted by an EventEmitter object?

e.g., can you do something like...

event_emitter.on(\         


        
12条回答
  •  春和景丽
    2020-12-24 00:44

    You might want to look into RPC modules for node.js. If I am not mistaken the Dnode RPC module has an chat server/client example similar to what you are trying to do. So you could either make use of their module or copy what they are doing.

    In brief the example shows a server which on connection creates listeners for all the server events from the connected client. It does this by simply iterating over a stored list of event names.

    var evNames = [ 'joined', 'said', 'parted' ];
    
    con.on('ready', function () {
        evNames.forEach(function (name) {
            emitter.on(name, client[name]);
        });
        emitter.emit('joined', client.name);
    });
    

    This code is clever because it automatically calls a remote procedure call on the client associated with the event when the event is emitted.

提交回复
热议问题