Marwen Trabelsi
Marwen Trabelsi

Reputation: 4257

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.

Upvotes: 0

Views: 80

Answers (1)

Mritunjay
Mritunjay

Reputation: 25882

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

Upvotes: 1

Related Questions