About Me

My photo
Web person at the Imperial War Museum, just completed PhD about digital sustainability in museums (the original motivation for this blog was as my research diary). Posting occasionally, and usually museum tech stuff but prone to stray. I welcome comments if you want to take anything further. These are my opinions and should not be attributed to my employer or anyone else (unless they thought of them too). Twitter: @jottevanger

Friday, March 27, 2009

Evaluate this

Schmuck that I am, and despite the fact that I've been doing javascript for a decade now (though not all that much in recent years), I'd never really got how useful the eval() method is. Today, I found one of those points where I could not continue without it and thought I'd just post up where it helped me since there will be others after the same solution.
My problem: to create/declare javascript variable names dynamically. I have a loop in this little SVG experiment I'm doing with the Raphael javascript SVG library (another post to come on this) where I want to make a "set" of SVG elements out of each item in an array of unknown length. I also need to attach an onclick function to each set. For creating the set, putting items into it, and attaching the event handler I need a variable name to be made on the fly. This is how to declare it:
eval("var r" +i +" = dynamically named variable'");
If i is currently 2, this creates a string variable with the name r2 and the value "dynamically named variable". To get the variable value you have to use the eval() method again, thus:
Probably old hat, this stuff, but I'm not too proud to show my ignorance, at least when I've just reduced it slightly!

No comments: