HTML and CSS Reference
In-Depth Information
Obtaining the Object Key
For the piece store, you used a key generator so the key is not part of the object. The code in the makeNextMove()
function will use the index based on the pos property to retrieve the object at the start position (and also at the
end position if there is a piece there). However, in order to update or delete an object you will need its key.
When retrieving the piece object at the start position, this code first gets the piece store from the transaction.
It then gets the piecePosition index from the store. To get the key value, you'll need to call index.getkey()
method which returns the key for the requested start position. This is stored in the startKey variable.
To get the desired object you'll call the index.get() method passing in the position to search for. This
returns the object at the requested start position and stores it in the oStart variable.
In both cases, the data is returned in the result property. Again, the event handlers that process the results
are nested.
With the necessary data obtained, the removePiece() method is called passing in the following parameters:
end - the ending position of the piece being moved
oStart - an object representing the piece being moved
startID - the key to the oStart object
pieceStore - the piece store that will be used to perform the update
Performing the Update
Now you'll implement the removePiece() function. This is perhaps misnamed since it will only remove a piece
when necessary. Add the following code to the end of the script element to implement the removePiece()
function removePiece(endPos, oStart, startKey, pieceStore) {
var index = pieceStore.index("piecePosition");
index.getKey(endPos).onsuccess = function (e4) {
var endKey =;
if (endKey) {
pieceStore.delete(endKey).onsuccess = function (e5) {
movePiece(oStart, startKey, endPos, pieceStore)
movePiece(oStart, startKey, endPos, pieceStore);
This code gets the key at the ending position. If there is a piece there, it calls the delete() method to
remove it and then calls the movePiece() function in the onsuccess handler for the delete() method. Notice
that it does not retrieve the object; only the key is needed to perform the delete. If there is no piece there, it
just calls the movePiece() function. When calling the movePiece() function, all the data it needs is passed to it
including the object, its key, the end position, and the object store that it will use.
Now you'll implement the movePiece() function that will finally perform the actual update. To update an
object you call the put() method. Unlike the add() method that you used earlier to add the pieces, the put()
method requires both the object and the key. If there is no object with the specified key, the object will be added.
Add the movePiece() method shown in Listing 11-10 to the end of the script element.
Search WWH ::

Custom Search