Using an In Memory Database in PhoneGap

List-Item Flow of Screens

A PhoneGap application often has the a master-detail flow of screens. A master screen contains a list of items such as list of products, posts, or people. When a row is selected in the list, the app transitions to a detail screen, showing the full details for the row. The list content is fetched from the server in one web service call, and the detail content is fetched from the server in a second web service call.

Maintaining Context

A back transition from the details screen, transitions the app to the list screen. The back transition has to return to the same context it left without an additional fetch from the server.

To maintain the list context, we store the list content once fetched from the server in an in-memory database, using the JavaScript TaffyDB database.

TaffyDB

TaffyDB offers MongoDB-like query/update capabilities:

For example,

  // Create DB and fill it with records
  var friends = TAFFY([
        {"id":1,"gender":"M","first":"John","last":"Smith","city":"Seattle,   WA","status":"Active"},
        {"id":2,"gender":"F","first":"Kelly","last":"Ruth","city":"Dallas, TX","status":"Active"},
        {"id":3,"gender":"M","first":"Jeff","last":"Stevenson","city":"Washington, D.C.","status":"Active"}    
 ]);

// Find all the friends in Seattle
friends({city:"Seattle, WA"});

// Find John Smith, by ID
friends({id:1});

// Find John Smith, by Name
friends({first:"John",last:"Smith"});

TaffyDb is made persistent by storing data in the browser local storage:

db.store("friends"); // starts storing records in local storage

Managing Context

When fetching the list content, we store the data in the database:

db().remove(); // clear old content
db.insert(data); // data fetched from server

When transitioning to the item screen, we first keep its id in local storage:

window.localStorage.setItem("itemId", id);

In the detail screen, we get the item id from local storage and fetch the full item details from the server.

When returning to the list screen, we check if we are back from the detail screen based in the presence of itemId in local storage:

if (window.localStorage.getItem("itemId")) { // back from item screen
   // remove itemId to return to a clean slate
   window.localStorage.removeItem("itemId");
   // retrieve the list content from the database
   var data = db().get();
   // render the screen
}
else{
   // fetch the list content again from the server
}