Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

594 CHAPTER 16 Offline web applications


var trans = db.transaction('authors', 'readonly');

Example of a transaction being opened in readwrite mode.
var trans = db.transaction('authors', 'readwrite');

Inserting a new record


After a transaction instance has been created, you can use it to add a new record. To do so,
you must first find the object store to which you would like to add the record. Call the add
method of the object store, which will insert the record asynchronously. The add method
returns a request instance in which you can subscribe to an onsuccess event that provides
notification when the operation is completed. You can then use the request.result property to
obtain the auto-generated id for the new record. You can also subscribe to the onerror event
if the operation fails, as shown in the following example.
var openRequest = indexedDB.open('Library', 1);
var db;

openRequest.onsuccess = function(response) {
db = openRequest.result;
addAuthor();
};

function addAuthor() {
var trans = db.transaction('authors', 'readwrite');
var authors = trans.objectStore("authors");
var request = authors.add({firstName: 'Daniel', lastName: 'Defoe'});
request.onsuccess = function(response) {
alert('New record id: ' + request.result);
};

request.onerror = function(response) { // display error };
}

Updating an existing record


Modifying existing objects is similar to adding a record, but instead of the add method, you
use the put method of the object store. Actually, you could use the put method for both
adding and updating values. The add method, however, can be used for new records only. An
exception is thrown if the add method is called using a key that already exists. The following
code demonstrates the use of the put method.
var openRequest = indexedDB.open('Library', 1);
var db;

openRequest.onsuccess = function(response) {
db = openRequest.result;
updateAuthor();
};
Free download pdf