I have a global variable which looks like this:
var socket_x = 'whatever';
The thing is that "x" would depend on the user session. Let's say the user id is 123, i want the global variable to be:
var socket_123 = 'whatever';
This way, each user browsing will have his own socket set as global variable.
I just don't know how to do this.
I know I can use:
eval('socket_' + userId) = 'whatever'; //not recommended
window['socket_' + userId] = 'whatever'; //best
but if I want to declare the global variable like this, it won't work:
var eval('socket_' + userId) = 'whatever';
Can someone help me on this one?
Thank you.
PS: I know "eval" should not be used for this but it's just for the illustration sake.
EDIT:
Thank you for your answer, all of you, but it just doesn't work.
This is what I have so far for my global variable (it works as it is but I don't want to mix php with javascript):
var socket_<?php echo $_SESSION['user_id'];?> = io.connect( 'http://pubsub.pubnub.com', pubnub_setup_private );
if I do this instead, like you suggest:
window['socket_'+actual_user_id]= io.connect( 'http://pubsub.pubnub.com', pubnub_setup_private );
it just won't work.
if I do this as a local variable, it works:
eval('socket_'+actual_user_id).emit( 'all', msg_all );
But if I do that, it doesn't:
window['socket_'+actual_user_id].emit( 'all', msg_all );
So I got 2 problems here:
I'm ok with avoiding eval but I just don't know how.
PS: I'm on a global context here.
window['socket_'+userId] = "whatever";
That should work just fine. Do NOT use eval
for something as trivial as this.
Although, even better would be an array:
socket[userId] = "whatever";
A variable attached to window
is a global variable. For example:
var myVar = 'hello';
alert( window.myVar );
... will alert 'hello' (assuming this code is run in the global context, of course).
EDIT: I would try ensuring your variable is being attached to the window
object by specifying it manually with window[xxx] = yyy
instead of var xxx = yyy
. This means it will always work even if it's in a function call. Try playing with this fiddle and see if you can break it the same way as your real code: http://jsfiddle.net/2hYfa/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With