简体   繁体   English

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

[英]Socket.io - Is it possible to pass callback functions as parameters in a socket emit event?

I was wondering if anyone knew if it was possible to pass callback functions in a socket.emit event? 我想知道是否有人知道是否可以在socket.emit事件中传递回调函数? 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... 这样可能吗...

 // 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, 问候,

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)中作为参数“ response”输入的任何值都可以在客户端回调中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM