Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

596 CHAPTER 16 Offline web applications


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

Understanding cursors


The other approach to finding records is by using cursors. A cursor can be opened by calling
the object store’s openCursor method, which returns a request object and accepts the follow-
ing parameters.
■■range This parameter allows you to provide a key range to limit records included in
the results.
■■direction By default, cursors are executed in ascending order. To change the order to
descending, use IDBCursor.PREV.
The following is a simple example that iterates through all records held in the authors
object store.
var openRequest = indexedDB.open('Library', 1);
var db;

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

function findAuthors() {
var trans = db.transaction('authors', 'readonly');
var authors = trans.objectStore("authors");
var request = authors.openCursor();

request.onsuccess = function(response) {
var cursor = response.target.result;

if (!cursor) {
alert('No records found.');
return;
}

alert('Id: ' + cursor.key + ' Last name: ' + cursor.value.lastName);
cursor.continue();
};

request.onerror = function(response) { // display error };
}
The cursor itself is on the result property of the response of the onsuccess event handler.
If no records are found, the onsuccess event will still fire, but the result will be undefined (or
null). If records are found, the cursor’s value property will contain the current record. To con-
tinue iterating, invoke the cursor’s continue method, which will trigger the onsuccess event
Free download pdf