简体   繁体   English

将数据传递给 Socket.io 回调

[英]Pass data to Socket.io callback

client.on('message', function(obj){});

This works fine, but I am trying to avoid nesting, so I take the callback function out like so:这很好用,但我试图避免嵌套,所以我将回调 function 取出,如下所示:

client.on('message', doThis(obj));

function doThis(obj) {}

But this gives me an error saying obj is undefined.但这给了我一个错误,说 obj 是未定义的。

How do I pass the message data to the callback function?如何将消息数据传递给回调 function?

Thanks谢谢

client.on('message', doThis);

function doThis(obj) {}

f(doThis) is the correct syntax. f(doThis)是正确的语法。 f(doThis(arg)) is the wrong syntax. f(doThis(arg))是错误的语法。

The latter is calling doThis immediately with the argument arg (which doesn't exist yet).后者使用参数arg立即调用doThis (尚不存在)。

That's why it says obj is undefined because your calling doThis immediatly.这就是为什么它说obj是未定义的,因为您立即调用doThis

What f(doThis) does is passes the function on instead of the return value of the function f(doThis)所做的是传递 function 而不是 function 的返回值

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

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