HTML and CSS Reference
In-Depth Information
Resetting the Board
You created the piece object store but have not populated it yet. You'll do that in a separate function. To
understand why, let me explain the database life cycle. The first time the web page is displayed, the database is
opened, and since it doesn't exist, a new database will be created. This happens because the onupgradeneeded
event is raised and you implemented this event handler to create the object stores. When the page is displayed
again (or simply refreshed), this step will be skipped since the database already exists.
Later, when you start moving the pieces around as well as deleting them, you'll want to move them
back to their initial position when the page is reloaded. You can use this method to do that. You'll now add a
resetBoard() function to the script using the following code. This will be called, not when the database is
created, but when the page is loaded.
function resetBoard() {
var xact = db.transaction(["piece"], "readwrite");
var pieceStore = xact.objectStore("piece");
var request = pieceStore.clear();
request.onsuccess = function(event) {
for (var i in pieces) {
This code creates a transaction using the read/write mode and specifies only the piece object store, since
that is the only one you'll need to access. Then the piece store is obtained from the transaction. The clear()
method is used to delete all of the objects from the store. Finally, all of the objects in the pieces[] array are
copied to the object store.
Now add the following code shown in bold to the onsuccess event handler. This will call the resetBoard()
function after the database has been opened.
The onupgradeneeded event is raised and its event handler must complete before the onsuccess event
is raised. This ensures that the database has been properly configured before it is used.
var request ="Chess", 1);
request.onsuccess = function (event) {
db =;
// Add the pieces to the board
Search WWH ::

Custom Search