Adding objects, arrays, and TTL support to storage (Become an expert)

At the very start of this book, I mentioned the need to use strings to store content in Local Storage. What if I said that it was possible to store objects and arrays in Local Storage as well? You'd be right in pointing out that these are not strings. You can still store content from data objects and arrays, if you use the power of JSON to convert them, as we will see in this recipe.

Getting ready

For this recipe, we will need our usual text editor, as well as the code that accompanies this book. We will also need a copy of the jStorage plugin that is available from http://github.com/andris9/jStorage/raw/master/jstorage.js, as well as jQuery; you can download this from http://code.jquery.com/jquery-1.8.3.min.js (or use the link as a CDN link).

How to do it...

Perform the following steps, for adding objects, arrays, and TTL support to storage:

  1. Let's begin by adding the following code to a new HTML document. Then, save it as addttlsupport.html:
    <!DOCTYPE html>
    <html>
      <head>
        <title>Getting Started with HTML5 local storage</title>
        <meta charset="utf-8">
        <script src=
        "http://code.jquery.com/jquery-1.8.3.min.js"></script>
        <script src="jstorage.js"></script>
        <script type="text/javascript" src="addttlsupport.js">
        </script>
        <link rel="stylesheet" 
        type="text/css" href="addttlsupport.css">
      </head>
      <body onload="load()">
      <div id="myform">
        <div id="results">
          <b>Simple form with name and age:</b><p>
          <div id="gTTL"></div>
        </div>
      </div>
      </body>
    </html>
  2. We also need to include the CSS styling for the page. Download the addttlsupport.css file from the code that accompanies this book, and save it in the same location as the main HTML file.
  3. We now need to add the basic framework for inputting values and calling the appropriate method handlers:
      <div id="gTTL"></div>
        <table>
          <tr>
            <td>Name:</td>
            <td><input type="text" id="name"></td>
          </tr>
          <tr>
            <td>Age:</td>
            <td><input type="text" id="age">
          </tr>
        </table>
        <p>   
          <table>  
            <tr>
              <td><input type="button" class="button medium 
              gray" id="addInfo" value="Add to Storage"></td>
              <td><input type="button" class="button medium 
              gray" id="getInfo" value="Get from Storage"></td>
              <td><input type="button" class="button medium 
              gray" id="gTTLbutton" value="Get TTL"></td>  
            </tr>
            <tr>
              <td><input type="button" class="button medium 
              gray" id="saveC" value="Save complex data"></td>
              <td><input type="button" class="button medium 
              gray" id="restoreC" value="Restore complex 
              data"></td> 
           </tr>
        </table>
  4. We need to add the code to handle the various functions required to manage LocalStorage. Go ahead and add the following into a file called addttlsupport.js, beginning with the save() method handler:
    function saveInfo() {    
      try {
        $.jStorage.set("name", $("#name").val());
        $.jStorage.set("age", $("#age").val());
        $("#name").val("");
        $("#age").val("");
        $.jStorage.setTTL("name", 30000);
      }
      catch (e) {
        if (e == QUOTA_EXCEEDED_ERR) {
          console.log("Error: Local Storage limit exceeds.");
        } else {
          console.log("Error: Saving to local storage.");
        }
      }
    }
  5. Next comes the method handler to retrieve content from LocalStorage:
    function getInfo() {
      console.log("Getting your data from local storage.");
      $("#name").val($.jStorage.get("name"));
      $("#age").val($.jStorage.get("age"));
    }
  6. We must not forget the check to ensure that we can even handle Local Storage. At this point, you should open the console in your browser, to see the output:
    function load() {
      if (typeof(Storage) == "undefined" ) {
        alert("Your browser does not support HTML5 
        localStorage. Try upgrading.");
      } else {
        console.log("Both localStorage and sessionStorage 
        support is there.");
      }
    }
  7. This method handler is responsible for saving data objects to LocalStorage.
    function sComplexData() {
      console.log("Saving complex data to local storage.");
      var personObject = new Object();
      personObject.name = $("#name").val();
      personObject.age = $("#age").val();
      $.jStorage.set("person", JSON.stringify(personObject));
    }
  8. And this one for retrieving them:
    function rComplexData() {
      console.log("Restoring complex data from local 
      storage.");
      var personObject = 
      JSON.parse($.jStorage.get("person"));
      $("#name").val(personObject.name);
      $("#age").val(personObject.age);
    }    
  9. Almost last but by no means least is the method for getting the TTL value for a named key:
    function getTTLforName() {
      var ttl = $.jStorage.getTTL("name");
      $("#gTTL").html("TTL time for 'name' key, 
      using simple store: " + ttl);
    }
  10. We finally need to add one more script. This provides all of the calls for each button:
      <script type="text/javascript" src="addttlsupport.js">
      </script>
      <script type="text/javascript">
        $("document").ready(function() {
          $("#getInfo").click(getInfo);
          $("#addInfo").click(saveInfo);
          $("#gTTLbutton").click(getTTLforName);
    
          $("#saveC").click(sComplexData);
          $("#restoreC").click(rComplexData);
        })
      </script>
  11. If all is well, you will see the following result when previewing this in your browser. This has already had the values Alex and 38 added to LocalStorage, using Add to Storage and the TTL value retrieved:
    How to do it...

How it works...

Read through the code carefully, do you notice anything in particular? One thing may pop out. We've used JSON to convert contents into strings before storing them. The keen-eyed amongst you would notice that we have actually used the same principles within the very first recipe in this book, Basic use of Local Storage.

We begin with the usual call to jQuery, followed by one to jStorage. We then have a number of functions that are used to either save content to, or retrieve from, LocalStorage. Our first two methods, save() and get(), are responsible for fetching and retrieving content from LocalStorage; the former includes a call to .setTTL() to set a TTL value 30000 or 30 seconds.

The next one, load(), performs a check when loading the web page, to ensure we use LocalStorage correctly. This is followed by sComplexData(), which creates a data object called personObject(), stores two values person and age within it, and then converts them into a key called person, using JSON, before storing them in LocalStorage. The rComplexData() handler retrieves the same person key, then parses it using JSON, before extracting the appropriate values and displaying them on the screen.

Note

The keen-eyed amongst you may have noticed that the code does not include support arrays. This is deliberate; I thought I would leave this as a recipe for you to complete! A hint, it uses the same method to store the content in LocalStorage; all you need to do is get the content into an array first.

So far, we've looked at using strings within our code, which works well. What if I say we could really turn the tables, and start to include images within LocalStorage? Yes, you heard right, images! We'll see how we can do that as part of the next recipe.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset