Lesson 2: Working with IndexedDB CHAPTER 16 591
onerror event that can notify your application if an error occurs during an attempt to con-
nect. The following example shows the open method.
var indexedDB = window.indexedDB;
var openRequest = indexedDB.open('Library', 1);
var db;
openRequest.onsuccess = function(response) {
db = openRequest.result;
};
openRequest.onerror = function (response) {
alert("Error code: " + response.target.errorCode);
};
In this example, the open method is called, and, within the onsuccess event handler, the db
variable is assigned a reference to the database object for later use.
Using object stores
In standard relational databases, tables are created that are defined by rigid schemas. Each
table contains a set of columns, each of which has a name and a data type. This doesn’t
allow for much flexibility because it requires a lot of work when schema changes are needed.
Therefore, instead of these table structures, IndexedDB uses spaces called object stores, which
are key/value storage areas.
Understanding versioning
Before creating a new object store, you need to understand how IndexedDB handles
versioning.
var openRequest = indexedDB.open('Library', 1);
In this call to open a database connection, a version number is passed as the second
parameter. The request object received contains an onupgradeneeded event that will be trig-
gered if the version requested doesn’t match the current version of the existing database. It
will also be triggered if the database does not yet exist. The onupgradeneeded event will be
fired before the onsuccess event.
The onupgradeneeded event is defined by the latest API specification. Earlier versions
handled versioning by a setVersion method on the database object. If you’re targeting older
browser versions, make sure to use the appropriate versioning method.
Within the onupgradeneeded event handler, use the createObjectStore method to allocate
a new storage area. This method requires an object store name and an object containing any
extra parameters to use in configuring the store.