简体   繁体   中英

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:

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

function doThis(obj) {}

But this gives me an error saying obj is undefined.

How do I pass the message data to the callback function?

Thanks

client.on('message', doThis);

function doThis(obj) {}

f(doThis) is the correct syntax. f(doThis(arg)) is the wrong syntax.

The latter is calling doThis immediately with the argument arg (which doesn't exist yet).

That's why it says obj is undefined because your calling doThis immediatly.

What f(doThis) does is passes the function on instead of the return value of the function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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