简体   繁体   English

如何为socket.on()传递更多参数

[英]How to pass more parameters for socket.on()

For socket.on("someChannel", handler), I hope to extract out my handler function to another file. 对于socket.on(“someChannel”,handler),我希望将我的处理函数提取到另一个文件中。 As such, they need to be passed in the socket obj and some more additional info. 因此,它们需要在套接字obj中传递,还有一些额外的信息。

Like: 喜欢:

socket.on("myEvt", myEvtHandler);

myEvtHandler(socket, additionalInfo, data) {//some stuff here}

But I can't. 但我不能。 The best I can think of is to do closure: 我能想到的最好的就是关闭:

(function(socket, addtionalInfo) {
    socket.on("myEvt", function(data) {
        myEvtHandler(socket, addtionalInfo, data);
    });
})(socket, addtionalInfo);

Is this correct? 它是否正确? Are there better ways? 还有更好的方法吗?

You can create a partial function using bind : 您可以使用bind创建部分函数:

socket.on("myEvt", myEvtHandler.bind(null, socket, additionalInfo));

The bind() will return a function with the first two arguments already 'filled in'. bind()将返回一个函数,前两个参数已经“填入”。 The first argument passed to bind() ( null in this case) is going to be the this object in your handler ( more info ). 传递给bind()的第一个参数(在本例中为null )将成为处理程序中的this对象( 更多信息 )。

Any additional arguments passed by socket.io to the handler will be available from the third argument onwards: socket.io传递给处理程序的任何其他参数将从第三个参数开始提供:

function myEvtHandler(socket, additionalInfo, data) { ... }

Similarly, this would do (almost) the same: 同样,这会(几乎)相同:

socket.on("myEvt", function(data) {
  myEvtHandler(socket, additionalInfo, data);
});

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

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