O'Reilly logo

Smashing Mobile Web Development by Greg Avola

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Elements to Build

Local storage is the main focal point in this chapter, so start by caching some of the data that you receive from external services. Before you start caching, you need to build a function that you can reference through this exercise to make interacting with local storage easier. Here you’ll write a function called myStorage, which includes the functionality you need to store data locally. You can then use this function every time you need to do this in your app.

Creating the myStorage function

When developing features that you will use all the time, sometimes it helps to write a basic function that you can call and iterate through your code.

1. In the index.html file, create a new variable called myStorage, which will contain a few methods:

var myStorage = {

set: function(a,b) {

},

remove: function(a) {

},

get: function(a) {

},

clear: function() {

}

}

While these functions may mimic the syntax of localStorage.setItem and localStorage.getItem, it’s nice to incorporate these methods in a function that you can change later. Say, for example, that you wanted to perform one action before saving something as a local storage element. You could just edit the code for the set function of myStorage once instead of scanning the whole file looking for instances of localStorage.setItem().

2. For the set method of myStorage, you pass two variables, a and b. In this case, a represents the index, or the key, while b represents the value.

..

set: function(a,b) {

var ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required