HTML and CSS Reference
In-Depth Information
In the resetBoard() function, you called the put() method (repeatedly - 32 times). However, you did not
get any response objects nor implement any event handlers. This code appears to be working synchronously.
Actually, these calls are processed asynchronously and a response object is returned in both cases but the return
value was ignored. You could implement both onsuccess and onerror event handlers for these requests. In this
case, you cheated a little. Since you don't need the result value like you would when retrieving data, you don't have
to handle the onsuccess event. Because these calls are within a transaction, subsequent use of the store will be
blocked until the updates are complete.
Tip
Drawing the Pieces
So far you have opened the database, configuring the object stores, if necessary. You have also populated
the piece store with the initial positions. Now you're ready to draw the pieces. To do that you'll implement a
drawAllPieces() function to iterate through all of the pieces and a drawPiece() function to display a single
image. These functions will be similar to the functions you created in Chapter 10 with the same names. However,
the data for these functions will be retrieved from the new database.
The drawAllPieces() function will use a cursor to process all of the objects in the piece object store.
For each piece, this will extract the necessary properties and pass them to the drawPiece() function. The
drawPiece() function must then access the pieceType store to obtain the type properties such as height and
width and then display the image in the appropriate location.
Using a Cursor
When retrieving data from an object store, if you want to retrieve a single record using its key, use the get()
method, which I will describe next. You can also select one of more objects using an index and I will explain
that later in this chapter. To get all the pieces you'll need to access the entire object store, which you'll do using a
cursor.
After creating the transaction and obtaining the object store, you'll call its openCursor() method. This
returns a DBResult object and you'll need to provide an onsuccess event handler for it. When the event fires, it
provides the first object only. You can obtain the next object by calling the continue() method. To demonstrate
this, add the function shown in Listing 11-6 to the script element.
Listing 11-6. Drawing the pieces
function drawAllPieces() {
var xact = db.transaction(["piece", "pieceType"]);
var pieceStore = xact.objectStore("piece");
var cursor = pieceStore.openCursor();
cursor.onsuccess = function (event) {
var item = event.target.result;
if (item) {
if (!item.value.killed) {
drawPiece(item.value.type,
item.value.color,
 
 
Search WWH ::




Custom Search