HTML5 and CSS3, Second Edition

(singke) #1
In the future, if we change the version to something else, the onupgradeneeded()
callback will fire again. This gives us an easy way to update schemas on the
user’s machine.

Now that we have our table, we can make this application actually do something.

Loading Notes


When the application loads, we want to connect to the database, create the
table if it doesn’t already exist, and then fetch any existing notes from the
database. Our connectToDB() method takes care of connecting and creating the
database, and on a successful connection, it calls fetchNotes(), which we need
to write next.

The fetchNotes() method will fetch all of the notes from the database. We define
it like this:

html5_indexedDB/javascripts/notes.js
varfetchNotes=function(){
varkeyRange,request,result,store,transaction;

transaction= db.transaction(["notes"],"readwrite");
store= transaction.objectStore("notes");

// Get everythingin the store;
keyRange= IDBKeyRange.lowerBound(0);
request= store.openCursor(keyRange);

request.onsuccess=function(event){
result= event.target.result;
if(result){
addToNotesList(result.key,result.value);
result.continue();
}
};

request.onerror=function(event){
alert("Unableto fetchrecords.");
};
};

This method grabs the results from the database using a cursor. If a result
is found, we call a method, addNoteToList(), which will add the note to the sidebar.
This process repeats for every record in the database thanks to the call to
result.continue(), which gets the next record, which invokes the onsuccess() callback
again. It’s a little bit of event recursion instead of a loop.

We need both the k e y and the data for the result. The k e y is the id field we
defined as the keypath, and the data is a JavaScript object containing the

report erratum • discuss

Storing Data in a Client-Side Database Using IndexedDB • 195


Download from Wow! eBook <www.wowebook.com>

Free download pdf