HTML and CSS Reference
In-Depth Information
Every object in a store must have a unique key. There are three ways to specify the key:
Use the
keypath parameter to specify one or more properties that define a unique key. As
objects are added, the keypath is used to generate a key based on the object's properties.
Use a key generator. If
autoIncrement is specified, the object store will assign a key based
on an internal counter.
Provide the key value when adding the object. If you don't specify a key path or use a key
generator, you must supply a key when adding an object to a store.
For the pieceType store you'll use a keypath . The name property will specify the type such as “pawn” or
“knight”. This will be a unique value for each object. This is also the value that will be used to retrieve an object so
this is a perfect candidate for a key path. After creating the object store the data from the pieceTypes[] array is
then copied to the pieceType store.
While in the onupgradeneeded event handler, data can be added to an object store without explicitly
creating a transaction. There is an implicit transaction created in response to the onupgradeneeded event.
Creating an Index
For the piece store there is no natural key available in the pieces data so you'll use a key generator. It will
generate unique keys but the keys will have no real meaning; they're just a surrogate key used to satisfy the
unique constraint. Initially when you're drawing the board you'll retrieve all of the objects so you don't need to
know what the key is.
Later you'll need to retrieve a piece so you can move it. You will find the desired piece based on its position
on the board. To facilitate that you'll add an index to the store based on the pos property. Since no two pieces can
occupy the same space, the pos property can be used as a unique index. By specifying this as a unique index, you
will get an error if you try to insert an object with the same position as an existing object.
Since the pos property is unique, you might be tempted to use it as the key. However, since you will be
moving pieces, their position will change and it's considered a poor design pattern to use a key that changes
often. For Indexed dB, this is especially problematic since you can't actually change a key; you must delete the
current object and then add it with the new key.
When creating an index you must specify a keypath like this:
("piecePosition", "pos", { unique: true });
In this case, the pos property is the keypath for this index. The keypath may include more than one property;
in which case the index will be based on the combination of the selected properties. When an object store has an
index, the index is automatically populated when an object is added to the store.
Search WWH ::

Custom Search