HTML and CSS Reference
In-Depth Information
If we do need to create an object store for this type then we are altering the structure of
the database. There are very strict rules for changing the structure of the database with In-
dexedDB, specifically, it can only occur during the process of opening the database.
In order to accommodate this requirement, we need to close the database, but before doing
that we will also record which version of the database we are using:
var version = database.version+1;
Now, the database can be re-opened, but we will tell IndexedDB that the version number
of the database has changed. We could request any version number for the database, but
incrementing by one is a natural choice.'DB', version);
Due to the fact that a new version number has been specified, not only will the onsuccess
and onerror functions be invoked on the request, but a third function called onupgraden-
eeded will also be invoked. This function is the only place where we are allowed to change
the structure of the database, and we do so with the following call:
request.onupgradeneeded = function(event) {
database =;
var objectStore = database.createObjectStore(type, { keyPath: "id", autoIncrement: true });
On the first line we are re-storing the local reference to the database.
Next we are requesting for an objectStore to be created for our type . We are also going to
specify that the primary key of the object store is contained in the id property of persisted
objects, and that we want this to be auto incremented by IndexedDB. This means that we
no longer need to worry about generating the IDs for objects. Notice that we still rely on
the onsuccess callback to invoke our callback method, otherwise we might start using the
object store before it has been created.
The API we have provided has complicated the object store creation process to some ex-
tent. If we knew all the object store names in the init method then we would not have
needed to close and reopen the database. It has given us more flexibility however, because
each functional area of the application can be responsible for initializing itself, without
worrying about the rest of the application.
Before proceeding with the code, we need to make a small change to this code in
Search WWH ::

Custom Search