简体   繁体   中英

How do I define a callback function in an outer scope using Node.js?

I've this code:

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
                         }

                };
    }

}

In order to make my code easier to read, I want to make setUsernameCallback function defined in an outer scope or maybe in another JS file, like that:

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
                             }

Actually, this is not working. I tried different ways to pass parameter but I'm still getting undefined socket .

You can define it like bellow

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

And pass the socket to function so it will be accessible

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

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