Socket.io Client: respond to all events with one handler?

前端 未结 14 1945
时光取名叫无心
时光取名叫无心 2020-11-28 04:16

Is it possible to have a socket.io client respond to all events without to have specify each event individually?

For example, something like this (which obviously do

14条回答
  •  一向
    一向 (楼主)
    2020-11-28 04:49

    Because your question was pretty general in asking for a solution, I'll pitch this one that requires no hacking the code, just a change in how you use the socket.

    I just decided to have my client app send the exact same event, but with a different payload.

    socket.emit("ev", { "name" : "miscEvent1"} );
    socket.emit("ev", { "name" : "miscEvent2"} );
    

    And on the server, something like...

    socket.on("ev", function(eventPayload) {
       myGenericHandler(eventPayload.name);
    });
    

    I don't know if always using the same event could cause any issues, maybe collisions of some kind at scale, but this served my purposes just fine.

提交回复
热议问题