Lesson 2: Working with IndexedDB CHAPTER 16 597
handler again, this time with the next record in the results. When it reaches the end of the
collection, the onsuccess event will have a null cursor.
Indexing cursors
Cursors can also be created by using an index of an object store. A standard cursor, like the
one in the previous example, can be created by using the openCursor method and will return
the entire object associated to the index value. However, if you only need the corresponding
keys and not the full object, you can use the openKeyCursor method instead.
The following is a modified version of the findAuthors method, which creates a cursor
against the lastName index instead of going directly against the object store. The sort order
is specified as IDBCursor.PREV, so the authors result is sorted by the last name in descending
order.
function findAuthors() {
var trans = db.transaction('authors', 'readonly');
var authors = trans.objectStore('authors');
var index = authors.index('lastName');
var request = index.openCursor(null, IDBCursor.PREV);
request.onsuccess = function(response) {
var cursor = response.target.result;
if (!cursor) {
alert('No records found.');
return;
}
alert('Index value (lastName): ' + cursor.key
+ ' First name: ' + cursor.value.firstName);
cursor.continue();
};
request.onerror = function(response) { // display error };
}
Applying key range limits
Most of the time, just a subset of an object store is needed instead of the entire contents. To
limit the results, pass an IDBKeyRange value as the first parameter to the openCursor method.
The following is a list of the various range methods available through the IDBKeyRange
object.
■■bound he most flexible range type is the bound method, by which you specify T
upper and lower limits and specify whether the outer bounds should be included in
the results. The bound range method accepts the following parameters.
■■lower pecifies the lower bound of the range.S
■■upper Specifies the upper bound of the range.