HTML5 and CSS3, Second Edition

(singke) #1
request object has a success() callback that fires when the connection is estab-
lished, and an error() method that fires when the connection doesn’t work.

In the success() callback, we call the fetchNotes() method, which we’ll build later.
This method will go through the database and load the notes into the sidebar.
But before we can do anything with the database, we have to create it.

Creating the Notes Table


Our notes table needs three fields:


Field Description
id The note’s unique identification
title The title of the note, for easy reference
Note The note itself

To create this table, we hook into a callback on the request object we created
in the connectToDB() method we just defined. The callback, onupgradeneeded(), fires
when the schema version number changes. In our case, our connectToDB()
method specifies a version and connects to a database that doesn’t exist yet.
The browser then fires the onupgradeneeded() callback because it knows we’ll
need to create a table. Add this code to the connectToDB():

html5_indexedDB/javascripts/notes.js
varconnectToDB=function(){
varversion= 1;
varrequest= window.indexedDB.open("awesomenotes", version);

➤ request.onupgradeneeded=function(event){
➤ alert("unupgradeneededfired");
➤ vardb = event.target.result;
➤ db.createObjectStore("notes", { keyPath:"id", autoIncrement:true});
➤ };
request.onsuccess=function(event){
db = event.target.result;
fetchNotes();
};
request.onerror=function(event){
alert(event.debug[1].message);
}
};

The createObjectStore() method defines the database table we’ll use. We pass in
the name of the table, followed by a hash of options. In our case, we’re
declaring that we want each record to have a unique, autoincrementing key
called id.

Chapter 9. Saving Data on the Client • 194


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf