在 Node.js 中,我有以下代码,可以正常工作:
var io = require('socket.io').listen(8082);
io.sockets.on('connection', function (socket) {
socket.on('message', function (msg) { console.log("message"); console.log(msg); socket.send('Your msg received [[' + msg + ']]'); });
socket.on('disconnect', function () { console.log("disconnect"); });
});
...但我想做的是以某种方式调用一个“外部”函数:
function fnParseMsg(msgArgInFunction)
{
// do some stuff with the msg...
console.log("message"); console.log(msgArgInFunction); socket.send('Your msg received [[' + msgArgInFunction + ']]');
};
var io = require('socket.io').listen(8082);
io.sockets.on('connection', function (socket) {
socket.on('message', fnParseMsg(msg));
socket.on('disconnect', function () { console.log("disconnect"); });
});
我想我以某种方式需要使用闭包;但我不确定如何...
最佳答案
要设置回调,您只需传递函数,而不是调用它,除非您调用的函数返回一个函数
socket.on('message', fnParseMsg);
此外,由于您想在 fnParseMsg
函数中使用 socket
,因此您需要传递它,因此可以通过两种方式执行此操作
socket.on('message', function(msg){
fnParseMsg(msg,socket);
});
或者使用 bind
socket.on('message', fnParseMsg.bind(null,socket));
调用函数时,bind
调用会将 socket
添加到参数列表中。您需要修改 fnParseMsg
声明以具有 socket
参数
//For the first snippet using the anonymous function
function fnParseMsg(msgArgInFunction,socket) {
//For the second snippet using bind
function fnParseMsg(socket,msgArgInFunction) {
关于javascript - 如何让 io.sockets.on 调用外部/全局函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24596671/