Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Practice exercises CHAPTER 16 613


? contacts.put(contact, currentRecord.key)
: contacts.add(contact);
request.onsuccess = function (response) {
ns.display();
};
};

Loading the list of contacts requires the use of a cursor to iterate through and build an
array of results. In the previous chapter, the results variable was a simple array of con-
tact records. In contrast, this code creates an array of objects that contain the object’s
key and the contact instance. After the cursor moves past the end of the data set, its
result object will be null.


  1. At the result object’s null point, call the bindToGrid method as follows.
    ns.display = function () {
    $('#currentAction').html('Add Contact');
    currentRecord = { key: null, contact: {} };
    displayCurrentRecord();


var trans = db.transaction('contacts', 'readonly');
var request = trans.objectStore("contacts").openCursor();
var results = [];

request.onsuccess = function (response) {
var cursor = response.target.result;

if (!cursor) {
bindToGrid(results);
return;
}

results.push({ key: cursor.key, contact: cursor.value });
cursor.continue();
};
};


  1. The loadContact method can now be changed to use the object store’s get method to
    find the selected record by its key, as follows.
    ns.loadContact = function () {
    var key = parseInt($(this).attr('data-key'));
    var trans = db.transaction('contacts', 'readonly');
    var store = trans.objectStore("contacts");
    var request = store.get(key);


request.onsuccess = function (response) {
$('#currentAction').html('Edit Contact');
currentRecord = { key: key, contact: response.target.result }
displayCurrentRecord();
};
};
No changes are needed within the displayCurrentRecord method.
Free download pdf