HTML5 and CSS3, Second Edition

(singke) #1

Creating and Connecting to the Database


Create the file javascripts/notes.js. We’ll put all of our application logic in this file.
Be sure to link it to the bottom of index.html, right above the <body> tag along
with jQuery, which we’ll use for event handling and easy Document Object
Model manipulation.

html5_indexedDB/index.html
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<scriptsrc="javascripts/notes.js"></script>

Inside javascripts/notes.js, we need to set up a few variables for our application.


html5_indexedDB/javascripts/notes.js
// Databasereference
vardb = null;
window.indexedDB= window.indexedDB|| window.mozIndexedDB||
window.webkitIndexedDB||window.msIndexedDB;

We’re declaring the db variable at the top of our script. Doing this makes it
available to the rest of the methods we’ll create. It puts the variable into the
global scope, and that’s not always a good idea. For this example, we’re
keeping the JavaScript code as simple as possible.

Then we define the window.indexedDB variable because, unfortunately, different
browsers have different names for this object. Lucky for us, although they
have different names, they work pretty much the same way, so we can create
one variable and reference it.

Let’s create a simple function that handles connecting to the database:


html5_indexedDB/javascripts/notes.js
varconnectToDB=function(){
varversion= 1;
varrequest= window.indexedDB.open("awesomenotes", version);
request.onsuccess=function(event){
db = event.target.result;
fetchNotes();
};
request.onerror=function(event){
alert(event.debug[1].message);
}
};

This uses the open() method on indexedDB to create the connection. We specify
a schema version when we connect, and we get a request object back. The

report erratum • discuss

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


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

Free download pdf