0

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.

0

1 Answer 1

1

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
2
  • what the benefit i get if i give a name to the anonymous function ? thx Commented Jul 31, 2014 at 6:15
  • 1
    I don't know any benefits if there are any. Commented Jul 31, 2014 at 6:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.