Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to use Javascript variables from a wider scope

How to use Javascript variables from a wider scope

Problem

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?

Problem courtesy of: eyurdakul

Solution

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 soc is overridden at each connection).

WebSocketNoaListener.onClientMessage = function(soc, msg){
  console.log("i can use message: " + msg);
  console.log("and the socket: " + soc.id);
};
WebSocketNoaListener.onClientDisconnect = function(soc, event){
  console.log("not implemented in question");
};
WebSocketNoaListener.onClientConnect = function(socket){
  socket.on("message", WebSocketNoaListener.onClientMessage.bind(this, socket));
  socket.on("disconnect", WebSocketNoaListener.onClientDisconnect.bind(this, socket));
}
Solution courtesy of: Adrien

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to use Javascript variables from a wider scope

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×