HTML and CSS Reference
In-Depth Information
Next we perform the request to save an object to the object store.
var objectStore = tx.objectStore(type);
var request = objectStore.put(obj);
request.onsuccess = function(event) {
obj.id = event.target.result
}
request.onerror = function(event) {
errorCallback('object_not_stored', 'It is not possible to store the object');
};
Once the object store has been retrieved from the transaction, the
put
method is used to per-
sist the object. This method is capable of supporting updates and inserts. If we only wanted
to handle inserts we could have used the
add
method instead.
Just as the transaction has callbacks, the code also adds
onsuccess
and
onerror
callbacks
to the
request
. In the
onsuccess
callback we are going to extract the ID that has been as-
signed to the object so that this can be returned to the client. The
onsuccess
of the request
will always be called before the
onsuccess
of the transaction
Next we will implement the
findAll
method. The following is the IndexedDB implement-
ation. This will introduce you to another important IndexedDB concept: cursors. Cursors
will be familiar to those of you who have worked with relational databases; a cursor rep-
resents a result set, and can be navigated to access all the records in the result set.
findAll : function(type, successCallback, errorCallback) {
if (!database) {
errorCallback('storage_api_not_initialized', 'The storage engine has not been initialized');
}
var result = [];
var tx = database.transaction(type);
var objectStore = tx.objectStore(type);
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
result.push(cursor.value);
cursor.continue();
} else {
successCallback(result);