我如何让io.sockets.on调用外部/全局函数?

时间:2014-07-06 14:05:17

标签: javascript node.js function scope closures

在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"); });
});

我想我不知何故需要使用一个闭包;但我不确定如何......

1 个答案:

答案 0 :(得分:1)

要设置回调,你只需传递函数,而不是调用它,除非你正在调用的函数返回一个函数

socket.on('message', fnParseMsg);

此外,既然你想要使用socket函数中的fnParseMsg,你需要传递它,你可以这两种方式

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) {