Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Practice exercises CHAPTER 16 615


};

function retrieveFromStorage() {
var contactsJSON = localStorage.getItem('contacts');
return contactsJSON? JSON.parse(contactsJSON) : [];
}

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();
};
}

function bindToGrid(results) {
var html = '';

for (var i = 0; i < results.length; i++) {
var key = results[i].key;
var contact = results[i].contact;
html += '<tr><td>' + contact.email + '</td>';
html += '<td>' + contact.firstName + ' ' + contact.lastName + '</td>';
html += '<td><a class="edit" href="javascript:void(0)" data-key=' +
key + '>Edit</a></td></tr>';
}

html = html || '<tr><td colspan="3">No records available</td></tr>';
$('#contacts tbody').html(html);
$('#contacts a.edit').on('click', ns.loadContact);
}

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 }
Free download pdf