我正在转换某些IndexedDB代码以使用YDN-DB,并需要一些帮助来转换它。如果页面已加载或重新加载,则此代码实际上会删除数据库,但在刷新页面时则不会删除。 我如何使用YDN-DB实现这一目标?
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
var db;
window.refreshing = false;
$(document).ready(function(){
if(window.performance) {
if(performance.navigation.type == 0 ) {
// The db already exists so delete it and re-create it so we don't have stale records.
deleteDB();
} else {
window.refreshing = true;
open();
}
}
});
function deleteDB() {
var request = indexedDB.deleteDatabase("DocsDB");
request.onsuccess = function() {
open();
}
request.onerror = function(event) {
throw "Error in deleteDB.";
}
}
function open() {
var request = indexedDB.open("DocsDB");
var upgraded = false;
request.onupgradeneeded = function(evt) {
upgraded = true;
var dbnew = evt.target.result;
dbnew.onerror = function(event) {
console.log("IndexedDB error: " + evt.target.error.code);
};
var objectStore = dbnew.createObjectStore(
"docs", { keyPath: "id", autoIncrement: true });
objectStore.createIndex("docname", "DOC_NAME", { unique: false });
objectStore.createIndex("printdate", "PRINT_DATE", { unique: false });
}
request.onsuccess = function(evt) {
db = request.result;
if (!upgraded && !window.refreshing) {
throw "Not upgraded";
}
request.result.onversionchange = function(e) {
if (e.newVersion === null) { // An attempt is made to delete the db
e.target.close(); // Manually close our connection to the db
}
};
if(typeof db != 'undefined' && !window.refreshing) {
// We load the store with the records here, attempting to add records via ajax doesn't work
// looks like we'll ahve to load them via ajax before initialization?
var store = getObjectStore(db);
for (i=0; i<documents["Rows"].length-1;i++) {
store.add(documents["Rows"][i]);
}
}
}
request.onerror = function() {
throw "Error in open";
}
}
function getObjectStore(db, mode = 'readwrite') {
if(typeof db != 'undefined') {
var tx = db.transaction('docs', mode);
return tx.objectStore('docs');
} else {
return null;
}
}
答案 0 :(得分:0)
删除数据库使用ydn.db.deleteDatabase("DocsDB")
。