HTML and CSS Reference
In-Depth Information
that you can perform subsequent actions. It is easy to overlook these situations, and they
can be a source of annoying bugs.
The next step in the process is to implement the save method. This will introduce you to
the concept of IndexedDB transactions:
save : function(type, obj, successCallback, errorCallback) {
if (!database) {
errorCallback('storage_api_not_initialized', 'The storage engine has not been initialized');
}
if (!obj.id) {
delete obj.id ;
} else {
obj.id = parseInt(obj.id)
}
var tx = database.transaction([type], "readwrite");
tx.oncomplete = function(event) {
successCallback(obj);
};
tx.onerror = function(event) {
errorCallback('transaction_error', 'It is not possible to store the object');
};
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');
};
}
After we establish that there is a database to operate on we check the id of the object we
have been passed. If it is a false value (e.g. null or “”) we delete the id property itself to
make it undefined . Since IndexedDB is responsible for generating keys, it does not expect
to find an id property at all on an unsaved object, even one with a null value. Our imple-
mentation of toObject will produce empty strings for properties that are empty.
Search WWH ::




Custom Search