Vous êtes sur la page 1sur 3

Creating and Connecting to the Database

Create the file javascripts/notes.js . Well 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 well 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>
<script src="javascripts/notes.js"></script>
Inside javascripts/notes.js , we need to set up a few variables for our application.
html5_indexedDB/javascripts/notes.js
// Database reference
var db = null;
window.indexedDB = window.indexedDB || window.mozIndexedDB ||
window.webkitIndexedDB ||window.msIndexedDB;
Were declaring the db variable at the top of our script. Doing this makes it
available to the rest of the methods well create. It puts the variable into the
global scope, and thats not always a good idea. For this example, were
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.
Lets create a simple function that handles connecting to the database:
html5_indexedDB/javascripts/notes.js
var connectToDB = function(){
var version = 1;
var request = 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 discussChapter 9. Saving Data on the Client
194
request object has a success() callback that fires when the connection is established, and an error() method that fires when the connection doesnt work.
In the success() callback, we call the fetchNotes() method, which well 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 notes 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 doesnt exist yet.
The browser then fires the onupgradeneeded() callback because it knows well
need to create a table. Add this code to the connectToDB() :
html5_indexedDB/javascripts/notes.js
var connectToDB = function(){
var version = 1;
var request = window.indexedDB.open("awesomenotes", version);

request.onupgradeneeded = function(event) {
alert("unupgradeneeded fired");
var db = 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 well use. We pass in
the name of the table, followed by a hash of options. In our case, were
declaring that we want each record to have a unique, autoincrementing key
called id .
report erratum discussStoring Data in a Client-Side Database Using IndexedDB
195
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
users 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 doesnt 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
var fetchNotes = function(){
var keyRange, request, result, store, transaction;
transaction = db.transaction(["notes"], "readwrite");
store = transaction.objectStore("notes");
// Get everything in 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);

Vous aimerez peut-être aussi