HTML5 and CSS3, Second Edition

(singke) #1
"title":title,
"note":note,
};

vartransaction= db.transaction(["notes"],"readwrite");
varstore= transaction.objectStore("notes");
varrequest= store.put(data);

request.onsuccess=function(event){
key = request.result;
addToNotesList(key,data);
newNote();
};
};

The insertNote() method adds the record into the database and uses the k e y
property of the result to get the ID for the record that was just created.
Remember, we set this to an autoincrementing field, so when we create a new
record, the database gives us a new unique ID for the record. Then we invoke
our addToNotesList() method to add the note to our list on the side of the page,
passing the key and the rest of the data. It also calls the newForm() method to
clear out the form.

Next we need to handle updates. The updateNote() method looks just like the
rest of the methods we’ve added so far:

html5_indexedDB/javascripts/notes.js
varupdateNote=function(id,title,note){
vardata,request,store,transaction;
id = parseInt(id);
data= {
"title":title,
"note":note,
"id": id
};

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

request.onsuccess=function(event){
$("#notes>li[data-id="+ id +"]").html(title);
};
};

When the record update is successful, we update the title of the note in our
list of notes by using jQuery to find the element in the sidebar whose data-id
attribute matches the value of the ID we just updated.

report erratum • discuss

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


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

Free download pdf