YDN-DB - 删除数据库然后在加载/重新加载页面时重新创建和加载,但在刷新时不重新加载

时间:2016-06-07 20:43:45

标签: ydn-db

我正在转换某些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;
    }
 }

1 个答案:

答案 0 :(得分:0)

删除数据库使用ydn.db.deleteDatabase("DocsDB")