HTML5 and CSS3, Second Edition

(singke) #1
note’s title and body. We pass both of those to addNoteToList() to add the note
to the sidebar. We define addNoteToList() like this:

html5_indexedDB/javascripts/notes.js
varaddToNotesList=function(key, data){
varitem= $("<li>");
varnotes= $("#notes");

item.attr("data-id", key);
item.html(data.title);
notes.append(item);
};

We’re embedding the ID of the record into a custom data attribute on the
element. We’ll use that ID to locate the record to load when the user clicks
the list item. We then add the new list item we create to the unordered list
in our interface, with the ID of notes.

We’re using jQuery’s attr() method to set the custom data attribute that holds
the ID. jQuery’s data() method can interact with custom data attributes,^5 but
the data() method has side effects when setting and retrieving HTML5 data-
values. Values retrieved by the data() method will be coerced to a data type
automatically, and using data() to set values saves the value to the jQuery
object rather than into the element’s data- attribute. So, for simplicity and
consistency, we’ll avoid jQuery’s data() method in this app.

Now we need to add code to load that item into the form when we select a
note from this list.

Fetching a Specific Record
We could add a click event to each list item, but a more practical and perfor-
mant approach is to watch any clicks on the unordered list and then determine
which one was clicked. This way, when we add new entries to the list (like
when we add a new note), we don’t have to add the click event to the new DOM
element we add to the list.

Add this event handler to javascripts/notes.js:


html5_indexedDB/javascripts/notes.js
$("#notes").click(function(event){
varelement= $(event.target);
if(element.is('li')) {
getNote(element.attr("data-id"));
}
});


  1. http://api.jquery.com/data/


Chapter 9. Saving Data on the Client • 196


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

Free download pdf