【问题标题】:How do I have io.sockets.on call an external/global function?如何让 io.sockets.on 调用外部/全局函数?
【发布时间】:2014-08-27 02:43:50
【问题描述】:

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

我想我需要以某种方式使用闭包;但我不确定如何...

【问题讨论】:

    标签: javascript node.js function scope closures


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,我会尝试这两种方法。有最佳实践吗?
    • 我不知道,我认为这正是你所喜欢的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2018-05-23
    • 2021-05-17
    • 1970-01-01
    • 2012-01-07
    相关资源
    最近更新 更多