I am writing a simple WebSocket application with socketio. There are 2 socket events that I can implement, on connect and on message. The first one takes the socket as parameter(client) and second takes the data sent from client. So I could write it this way to use the socket variable in on message event:
WebSocketNoaListener.onClientConnect = function(socket){
var soc = socket;
socket.on("message", function(msg){
console.log("i can use message: "+msg);
console.log("and the socket: "+soc.id);
});
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect);
}
But i want to separate my functions for better readability:
WebSocketNoaListener.onClientConnect = function(socket){
var soc = socket;
socket.on("message", WebSocketNoaListener.onClientMessage);
socket.on("disconnect", WebSocketNoaListener.onClientDisconnect);
}
WebSocketNoaListener.onClientMessage = function(){...
I would need to use the soc variable in a scope outside the function that receives socket. Is that possible?
You should really do something like this instead of polluting the global space (moreover, the solution given in the two other answers wont be able to handle two simultaneous connections, because
socis overridden at each connection).