Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 2: Working with IndexedDB CHAPTER 16 595


function updateAuthor() {
var trans = db.transaction('authors', 'readwrite');
var authors = trans.objectStore("authors");
var request = authors.put({firstName: 'Bob', lastName: 'Defoe'}, 1);
request.onsuccess = function(response) {
alert('Updated record id: ' + request.result);
};

request.onerror = function(response) { // display error };
}
The preceding example updates the first and last names of the author record with a
key of 1.

Deleting a record


To remove a stored object, you only need to know its key value, which is passed to the delete
method of the object store.
function deleteAuthor() {
var trans = db.transaction('authors', 'readwrite');
var authors = trans.objectStore("authors");
var request = authors.delete(1);

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

Retrieving a record


Several methods are available for finding existing records. If you need to find a specific
record, use the get method of the object store. The only parameter needed to pass to the
method is the key of the object being retrieved. Like other operations, this needs to be done
within a transaction. In the following example, the transaction mode is set to readonly.
var openRequest = indexedDB.open('Library', 1);
var db;

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

function getAuthor() {
var trans = db.transaction('authors', 'readonly');
var authors = trans.objectStore("authors");
var request = authors.get(1);

request.onsuccess = function(response) {
var author = response.target.result;
alert('Last name: ' + author.lastName);
};
Free download pdf