Saving the book list

Let’s come back to our book wish list example.

The first step is to use local storage to store the books array.

The new data object that loads and save book list on data change.

1// retrieve saved book list
2data.books = JSON.parse(localStorage.getItem("books")) || [];
3
4// save book list
5data.saveToLocal = function() {
6  localStorage.setItem("books", JSON.stringify(this.books));
7}

Whenever we have changes on book list, we save it.

 1data.addBook = function(title, isbn) {
 2  this.books.push(new Book(title, isbn));
 3  this.saveToLocal();  // <-- Save changes
 4};
 5data.removeBook = function(isbn) {
 6  for(var i=0, len=data.books.length; i<len; i++) {
 7    var book = data.books[i];
 8    if (book.isbn === isbn) {
 9      this.books.splice(i, 1);
10      this.saveToLocal();  // <-- Save changes
11      return;
12    }
13  }
14}

What’s next? We’re going to take a look at “Adding tags as string”.

overlaied image when clicked on thumbnail

Makzan | Mobile web app dev with phonegap | Table of Content