Game Development Reference
In-Depth Information
of this storage system. This event is the onupgradeneeded (that is, on upgrade
needed) event. This will be fired when the database is first created and, as you might
expect, whenever the version number used to open the database is higher than the
last value used when the database was opened, as shown in the following code:
var dbName = "myDatabase";
var dbVersion = 1;
var db = null;
var store = null;
var request = indexedDB.open(dbName, dbVersion);
request.onupgradeneeded = function(event) {
db = event.target.result;
store = db.createObjectStore("myDataStore",
{keyPath: "myKey"});
};
The call to createObjectStore made on the database object takes two paramet-
ers. The first is a string representing the name of the object store. This store can be
thought of as a table in the world of relational databases. Of course, instead of in-
serting records into columns from a table, we insert whole objects into the data store.
The second parameter is an object defining properties of the data store. One import-
ant attribute that this object must define is the keyPath object, which is what makes
each object we store unique. The value assigned to this property can be anything we
choose.
Now, any objects that we persist in this data store must have an attribute with the
same name as the one assigned to keyPath . In this example, our objects will need
to have an attribute of myKey . If a new object is persisted, it will be indexed by the
value of this property.
Any additional objects stored that have the same value for myKey will replace any
old objects with that same key. Thus, we must provide a unique value for this object
every time we want a unique object persisted.
Alternatively, we can let the browser provide a unique value for this key for us. Again,
comparing this concept to a relational database, we can think of the keyPath ob-
ject as being the same thing as a unique ID for a particular element. Just as most
relational database systems will support some sort of auto increment, so does In-
Search WWH ::




Custom Search