Wednesday 10 December 2008

Making javascript remember things

OK Geek Post Alert!

If you have been following my JS posts you will know that I quite like it as a language .. now there comes a time in most coder's life when they get to a point in some code where they need a global variable and they have that "DUH!" moment and have to scoot back up to the top of their code to define a var in a place that will define it as global... well here is a way around that.

There is a global object in JS ... i'm waiting ... that's right Edgerton-Smythe the window object and can we use it? YES WE CAN ! Paulson PUT Bigglesworth down this instant or I SHALL send you to the padre!

Lets say we want to tweak a value the user has entered and come back to it later say in the form submission JS. I would use this bit of JS that I keep in my "tool box" javascript library.

function dontforget(theValueToRemember,theNameIWillCallIt)
{
      window[theNameIWillCallIt] = theValueToRemember;
}
For example I want to remember the pearson's age in years that I have calculated from their birthday which they entered in date format but I dont have a global variable to hold the age defined in my code so I use this :

      dontForget(56,"theirAge");

Then I go off do other things, slip out of the function I was in and come back to the value I memorized at any time by simply looking in window.theirAge or window["theirAge"].

Please be aware I am not advocating the fullscale use of this .. you should declare all your vars and scope them correctly, but if you have to write quick code for whatever reason and find yourself needing a global var, this is a method you can use.

Disqus for Domi-No-Yes-Maybe