HTML and CSS Reference
In-Depth Information
you will specify a key when adding an object to the store. Alternatively, you can use a key generator , where the
object store will assign incremental key values for you. The following code demonstrates these alternatives:
// Using an inline key
var typeStore = db.createObjectStore("pieceType", { keyPath: "id" });
// Using an out-of-line key
var sampleStore = db.createObjectStore("sample", { });
sampleStore.add(sample, 5);
// Using a key generator
var pieceStore = db.createObjectStore("piece", { autoIncrement: true });
As its name implies, you can also create an index on an object store; in fact you can create as many indices as
you want. An index enables you to find a specific object or collection of objects quickly. An index is a collection of
name-value pairs, where the value is a key into the object store. For example, if you have a customer object store
and wanted to search by last name you can create an index on the lastName property of the object. The database
will automatically create an entry in the index for each object in the store. This entry will contain the last name
and the corresponding key to that object. The following code demonstrates how to use an index:
// Create an index on the lastName property
customerStore.createIndex("lastName", "pos", { unique: true });
// Get the index
var index = custStore.index("lastName");
index.get(lastName).onsuccess = function(); // get the object
index.getKey(lastName).onsuccess = function(); // get the key
Indexed DB does not support relationships between object stores. You can't enforce a foreign key
relationship for example. You can certainly use foreign keys, where a property in one object store is a key into
another, as I will demonstrate later. However, the database does not enforce this constraint. Also, you can't
perform joins between objects stores.
Processing Asynchronously
A key aspect of Indexed DB that may take some getting used to is its asynchronous processing; almost all
database operations are done asynchronously. The general pattern is to call a method to perform a database
operation such as opening a database or retrieving a set of records (objects). This will return a request object.
You must then implement the onsuccess and onerror event handlers for that request object. If the request was
successful, the onsuccess handler is called and the result of the method call is passed through the event object.
The onerror event is bubbled up the hierarchy. For example, an error that occurs on the request object, if
not handled will be raised on the transaction object. If not handled there it will be raised on the database object. In
many cases, you can just use a single event handler at the database level and handle all the errors there.
Search WWH ::

Custom Search