0

I want to use local session storage to maintain state in my web app, especially if/when the user opens several tabs in his browser.

I have some data that is injected in the HTML on the server. In the document.ready section of the page, I have something like this:

MyStorage = window.sessionStorage;
MyStorage.setItem('MyVar', $('#TheVar').html());

If later on I write this:

ThisVar = MyStorage.getItem('MyVar');
ThisVar = 3;

Will the value in the session storage also become 3? And, will the value of all the variables ThisVar in other tabs also be 3 when I change the value of ThisVar in one tab?

Thanks.

frenchie
  • 51,731
  • 109
  • 304
  • 510
  • No because you are changing, the local variable ThisVar, you would have write the value back into your sessionStorrage. – mas-designs Mar 05 '12 at 13:51

2 Answers2

3
  1. No, because you're assigning a new value to ThisVar, not to the sessionStorage key-value pair.
  2. No, the variables are not magically updated. getItem returns the value, thus the string of the stored key.
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Then is there a way to assign its reference instead? – frenchie Mar 05 '12 at 13:51
  • @frenchie You have to use `sessionStorage.getItem('MyVar')` whenever you want the latest value. – Rob W Mar 05 '12 at 13:53
  • 1
    ok, thanks, I got it. It would only work for objects because objects are reference types but sessionStorage only works with strings and these are only passed by value; is that correct? – frenchie Mar 05 '12 at 13:56
  • @frenchie Yes, you are correct. Here's a link to the documentation, for future visitors: https://developer.mozilla.org/en/DOM/Storage#sessionStorage – Rob W Mar 05 '12 at 14:00
  • Rob, I was wondering if you could look at this question: http://stackoverflow.com/questions/9561138/javascript-warning-on-closure-compiler – frenchie Mar 05 '12 at 14:59
0
  1. try to avoid Uppercase variables, this naming-convention is for Classes only.
  2. use the keyword var to initialise you variables.

  3. (answer to your question) No. You are not working on references, the localStorage.getItem()function returns the value as string, and not as a reference. You need to use the localStorage.setItem() function as you did in the first place, to update the Storage. Thats why, I'd recommend you work directly on the storage and not use extra variables. (On the other hand you could use a function, which updates the storage when you change the value of your variable.)

Christoph
  • 50,121
  • 21
  • 99
  • 128