Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading and writing from localStorage?

I just started to study Phonegap + jQuery Mobile and HTML5,, so don't loose your nerve with my idiocy!

Could somebody tell me why this is not working? When I am using a variable from localStorage, I just get an empty screen when pressing the button, but when using a variable temperature="100", it is working fine. Android 4.1.

<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
  window.localStorage.setItem("temperature", "100");
  var temperature = window.localStorage.getItem("temperature");
}
</script>
<div data-role="content">
  <p>Working or not?</p>
  <button onclick="myFunction()">Try it</button>
  <p id="testi"></p>
<script type="text/javascript">
  function myFunction() {
    //var temperature = "100";----> This is working!
    document.getElementById("testi").innerHTML = temperature;
  }
 </script>
</div>

Another question: How to handle variables between pages in Windows Phone? They are not supporting localStorage, so is there another way to handle this if you haven't got db-connection?

Thanks!

Sami

like image 850
Sami Avatar asked Jul 15 '12 09:07

Sami


People also ask

Is reading from localStorage slow?

Local storage stores the data on your user's hard drive. It takes a bit longer to read and write to the hard drive than it does to RAM. The conclusion to take away from this is that you could optimize your performance by reading from local storage on start up and only write to it when the user logs out.

Is it good practice to use localStorage?

In basic terms, local storage enables developers to store and retrieve data in the browser. It is critical to understand, though, that using localStorage as a database for your project is not a good practice, since data will be lost when the user clears the cache, among other things.

Is localStorage editable?

Once the information is stored in the client, it's always editable.


1 Answers

temperature is local to the scope of the onDeviceReady function. That is, once the function is over, it's gone.

You have two options:

// Make it global
var temperature;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
  window.localStorage.setItem("temperature", "100");
  temperature = window.localStorage.getItem("temperature");
}

or:

// Retrieve it in myFunction
function myFunction() {
  var temperature = localStorage.getItem("temperature");
  document.getElementById("testi").innerHTML = temperature;
}

For a good list of examples of function scope, try this answer.

like image 64
brymck Avatar answered Oct 05 '22 18:10

brymck