socket.io事件和自定义事件

时间:2022-08-22 16:32:13
connection
disconnect
custom-event

Are these string available somewhere on the socket object on the server-side? in case the socket object is passed around, otherwise I'll passing another param with event as well and function signature would be as follows.

这些字符串是否可以在服务器端的套接字对象上找到?如果套接字对象被传递,否则我将传递另一个带事件的参数,函数签名如下。

io.on('connection', function(socket) {
   doSomething(socket, 'connection');

   socket.on('disconnect', function(){
       doSomething(socket', 'disconnect');
   }
}


function doSomething(socket, eventName) { 
    // is there a way to get this event name from socket object itself?

}

1 个解决方案

#1


1  

Are these string available somewhere on the socket object on the server-side?

这些字符串是否可以在服务器端的套接字对象上找到?

No. If you want an event name passed to your function, you need to pass it yourself like your own example shows. It is not part of the socket object because (with async operations in-flight) multiple events could be in-flight at the same time so the socket object is not a safe place to store the "current" event.

不可以。如果您希望将事件名称传递给您的函数,则需要自己传递它,就像您自己的示例所示。它不是套接字对象的一部分,因为(在飞行中具有异步操作)多个事件可以同时在飞行中,因此套接字对象不是存储“当前”事件的安全位置。

#1


1  

Are these string available somewhere on the socket object on the server-side?

这些字符串是否可以在服务器端的套接字对象上找到?

No. If you want an event name passed to your function, you need to pass it yourself like your own example shows. It is not part of the socket object because (with async operations in-flight) multiple events could be in-flight at the same time so the socket object is not a safe place to store the "current" event.

不可以。如果您希望将事件名称传递给您的函数,则需要自己传递它,就像您自己的示例所示。它不是套接字对象的一部分,因为(在飞行中具有异步操作)多个事件可以同时在飞行中,因此套接字对象不是存储“当前”事件的安全位置。