Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

592 CHAPTER 16 Offline web applications


Using the keypath property
One important property of the parameter object is the keypath. Its purpose is to specify
which property on the value object should be used as the key. This key is then used as the
primary index for stored instances. If the property specified by the keypath does not exist on
the value object, you must use a key generator such as autoIncrement, which creates auto-
incrementing numeric keys for you as follows.
var openRequest = indexedDB.open('Library', 1);
openRequest.onupgradeneeded = function(response) {
response.currentTarget.result.createObjectStore("authors",
{ keypath: 'id', autoIncrement: true });
};

In this example, a new object store called “authors” is created. Notice that you are not
required to identify the properties explicitly or even identify the type of object that will be
stored. However, this example allows IndexedDB to create the keys by setting the autoIncre-
ment property to true. You just as easily could specify a field on the value object as the key.
You could use the following code example if each author had an email that you would like to
use as the key.
response.currentTarget.result.createObjectStore("authors", { keypath: 'email' });

Adding indexes
Although the key will be the primary index for object stores, you can specify other indexes.
This can provide a performance boost if properties other than the key might be commonly
used in sorting or filtering. To do so, use the createIndex method on the object store, which
has the following parameters.
■■name The index name.
■■keyPath pecifies the property on the value object for which the index will be S
created.
■■optionalParameters Optional parameter that can contain an object with proper-
ties used for advanced index settings. Currently, IndexedDB supports two advanced
settings. The first is ‘unique’, which when true adds a constraint to the property that
prohibits two records from having the same value. The second property that can be
set is ‘multiEntry’, which indicates how the index should behave when the keyPath is an
array. If set to true, an index entry is created for each value in the array. If set to false, a
single index entry is created for the array as a whole.
The following demonstrates the use of the createIndex method on the object store to a
new, non-unique index for the lastName property of the authors object store.
var openRequest = indexedDB.open('Library', 2);
openRequest.onupgradeneeded = function(response) {
var store = response.currentTarget.transaction.objectStore("authors");
store.createIndex('lastName', 'lastName', { unique: false });
};
Free download pdf