HTML and CSS Reference
In-Depth Information
These calls will all be made using the same transaction. As I demonstrated at the beginning of the chapter,
you'll need to nest the
onsuccess
event handlers for each of these calls. Add the
makeNextMove()
function shown
in Listing 11-9 to the end of the
script
element.
Listing 11-9.
Implementing the makeNextMove() function
function makeNextMove() {
var xact = db.transaction(["move", "piece"], "readwrite");
var moveStore = xact.objectStore("move");
moveStore.get(moveNumber).onsuccess = function (e1) {
var startPos = e1.target.result.start;
var endPos = e1.target.result.end;
var startKey = null;
var oStart = null;
var pieceStore = xact.objectStore("piece");
var index = pieceStore.index("piecePosition");
index.getKey(startPos).onsuccess = function (e2) {
startKey = e2.target.result;
index.get(startPos).onsuccess = function (e3) {
oStart = e3.target.result;
// If there is a piece at the ending location, we'll
// need to update it to prevent a duplicate pos index
removePiece(endPos, oStart, startKey, pieceStore);
}
}
}
}
This function creates a transaction that will access both the
move
and
piece
store. The mode is set to
“readwrite” because the objects in the
piece
store will be modified. It then gets the
move
store and calls its
get()
method specifying the current move, which is the key to the table. This will return a single object and the
start
and
end
positions are extracted from the result in the
onsuccess
event handler.
■
Notice that this code doesn't explicitly define a request variable. Instead the
onsuccess
event handler is
attached directly to the database call. In the previous examples I declared a request variable and then attached the
event handler to it to help you see what was happening. However, attaching the event handler directly to the method
accomplishes the same thing but simplifies the code a little.
Tip