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 ...

Get Smashing Mobile Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.