614 CHAPTER 16 Offline web applications
Because the results array that’s passed to the bindToGrid method contains objects that
are slightly more complex, the for loop needs some modifications. Remember that
the data key is now the object’s primary key instead of just its index. Your bindToGrid
method should look like the following.
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);
}
When you finish, the final JavaScript file should be similar to the following.
/// <reference path="jquery-1.8.3.js" />
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.
webkitIndexedDB || window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction;
window.IDBCursor = window.IDBCursor || window.webkitIDBCursor;
$(document).ready(function () {
contactsNamespace.initialize();
});
(function () {
this.contactsNamespace = this.contactsNamespace || {};
var ns = this.contactsNamespace;
var db;
var currentRecord;
ns.initialize = function () {
$('#btnSave').on('click', ns.save);
var request = indexedDB.open('Chapter16', 1);
request.onupgradeneeded = function (response) {
var options = { keypath: 'id', autoIncrement: true };
response.currentTarget.result.createObjectStore("contacts", options);
};
request.onsuccess = function (response) {
db = request.result;
ns.display();
};