如何使用Node.js在外部作用域中定义回调函数?

时间:2014-07-31 05:56:57

标签: javascript node.js callback

我有这段代码:

for (i in namespaces) 
{
    namespaces[i].on('connection',handleConnection(namespaces[i]));  

    function handleConnection(ns)
    {

        return function (socket){//connection

                    socket.on('setUsername',setUsernameCallback);//event received

                    function setUsernameCallback(userN){//I want to move this 
                       socket.username = userN;
                       //some code
                         }

                };
    }

}

为了使我的代码更容易阅读,我想在外部作用域中定义setUsernameCallback函数,或者在另一个JS文件中定义,如:

for (i in namespaces) 
{
    namespaces[i].on('connection',handleConnection(namespaces[i]));  

    function handleConnection(ns)
    {

        return function (socket){//connection

                    socket.on('setUsername',setUsernameCallback);//event received

                };
    }

}




 function setUsernameCallback(userN){
                           socket.username = userN;
                           //some code
                             }

实际上,这不起作用。我尝试了不同的传递参数的方法,但我仍然得到未定义的套接字

1 个答案:

答案 0 :(得分:1)

你可以像下面那样定义它

var setUsernameCallback = function(socket){
    return function(userN){
        socket.username = userN;
        //some code
     }
}

并将socket传递给函数,以便可以访问

socket.on('setUsername',setUsernameCallback(socket));//event received