Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

612 CHAPTER 16 Offline web applications



  1. The names of the IndexedDB variables with which you’ll need to work vary across dif-
    ferent browsers. Handle those differences by adding the following to the top of the
    ContactsLibrary.js file.
    window.indexedDB = window.indexedDB || window.mozIndexedDB ||
    window.webkitIndexedDB || window.msIndexedDB;
    window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction;
    window.IDBCursor = window.IDBCursor || window.webkitIDBCursor;

  2. Prepare to add a database instance that’s accessible to all methods in the namespace
    by adding a db variable at the start of the immediately invoked function expression
    (IIFE) function.
    this.contactsNamespace = this.contactsNamespace || {};
    var ns = this.contactsNamespace;
    var db;
    var currentRecord;

  3. Within the initialize method, create the contacts object store and open the database
    connection. Instead of just relying on an item’s index within the total resultset, allow
    IndexedDB to create an auto-incremented key as follows.
    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();
};
};


  1. Convert the remaining methods in the order in which they appear in the JavaScript file,
    starting with the save method. Within it, start a readwrite transaction against the con-
    tacts store. If updating an existing record, use the put method. If adding a new record,
    use the add method.
    Notice that this occurs asynchronously.
    ns.save = function () {
    var contact = currentRecord.contact;
    contact.firstName = $('#firstName').val();
    contact.lastName = $('#lastName').val();
    contact.email = $('#email').val();
    contact.phoneNumber = $('#phoneNumber').val();


var trans = db.transaction('contacts', 'readwrite');
var contacts = trans.objectStore("contacts");
var request = currentRecord.key != null
Free download pdf