Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: dynamically named global variable

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:

  • window never works for me, eval does.
  • eval works as a local variable but not as a global one. It seems that "var" is needed but using "var" just before eval is not accepted.

I'm ok with avoiding eval but I just don't know how.

PS: I'm on a global context here.

like image 650
Baylock Avatar asked May 14 '12 16:05

Baylock


2 Answers

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";
like image 98
Niet the Dark Absol Avatar answered Sep 17 '22 20:09

Niet the Dark Absol


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/

like image 24
kitti Avatar answered Sep 21 '22 20:09

kitti