Socket.io - 是否可以将回调函数作为套接字发出事件中的参数传递?

时间:2022-03-19 19:43:17

I was wondering if anyone knew if it was possible to pass callback functions in a socket.emit event? The reason I'm asking is I would like to pass some data as a parameter ONLY IF it has been uploaded in the form. To be more specific, a user can create a status that allows him to upload an image and a string of text IF he wants to but it is NOT REQUIRED. Is something like this possible...

我想知道是否有人知道是否有可能在socket.emit事件中传递回调函数?我问的原因是我想将一些数据作为参数传递,只要它已在表单中上传。更具体地说,用户可以创建一个状态,允许他上传图像和一串文本,如果他想要,但不是必需的。这样的事情可能......

 // Client side code
 socket.emit('an event', required_data, function(){
   if(the string of text was included)
   {
      pass it as a parameter in the socket emit event
   }
 }, 
 function(){
    if(the image was included)
    {
      pass it as a parameter in the socket emit event
    }
 });

If anyone can offer some advice on how it can be done it would be appreciated. Regards,

如果有人能就如何做到这一点提出一些建议,我们将不胜感激。问候,

1 个解决方案

#1


0  

I'm not realy sure what you want but as for an answer to your question title i would say yes you can have a callback to socket.emit like this

我不确定你想要什么但是对于你的问题标题的答案我会说是的你可以回调socket.emit像这样

CLIENT :

socket.emit('event', data, function(response){
    do something
})

SERVER :

socket.on('event',function(data, fn) {
    // do whatever
    fn(response)     // callback of emit
})

Here whatever value you put as parameter 'response' in fn(response) would be available in clientside callback.

无论您在fn(响应)中作为参数'response'放置的值都可以在客户端回调中使用。

#1


0  

I'm not realy sure what you want but as for an answer to your question title i would say yes you can have a callback to socket.emit like this

我不确定你想要什么但是对于你的问题标题的答案我会说是的你可以回调socket.emit像这样

CLIENT :

socket.emit('event', data, function(response){
    do something
})

SERVER :

socket.on('event',function(data, fn) {
    // do whatever
    fn(response)     // callback of emit
})

Here whatever value you put as parameter 'response' in fn(response) would be available in clientside callback.

无论您在fn(响应)中作为参数'response'放置的值都可以在客户端回调中使用。