HTML and CSS Reference
In-Depth Information
the need to loop through all the objects. This is because IndexedDB has an index on the
id
property:
findById : function (type, id, successCallback, errorCallback) {
if (!database) {
errorCallback('storage_api_not_initialized', 'The storage engine has not been initialized');
}
var tx = database.transaction([type]);
var objectStore = tx.objectStore(type);
var request = objectStore.get(id);
request.onsuccess = function(event) {
successCallback(event.target.result);
}
request.onerror = function(event) {
errorCallback('object_not_stored', 'It is not possible to locate the requested object');
};
}
This method is very similar to the
findAll
method, except we do not need to open a cursor
to find the object we wish to access, instead we can call
get
on the object store and pass in
the relevant
id
.
As with all IndexedDB methods, this is still an asynchronous call, therefore we still need
to add an event listener to retrieve the object returned. If there is no match for the key,
get
will return a null result, which is also what our storage engine API expects.
The delete implementation is similar to several of the methods we have seen before:
delete : function(type, id, successCallback, errorCallback) {
var obj = {};
obj.id = id;
var tx = database.transaction([type], "readwrite");
tx.oncomplete = function(event) {
successCallback(id);
};
tx.onerror = function(event) {
console.log(event);
errorCallback('transaction_error', 'It is not possible to store the object');