我对JS有一定的了解,但最终仍在学习中。我试图在IndexedDB上重新创建一个PHP / mySQL项目,但无法弄清为什么在这里看到错误。

IndexedDB连接按预期方式工作。第一个函数(createItem)正常运行,但是第二个函数(getItems)返回错误,声称“ db”变量未定义。这是一个全局变量,因此应该可以通过函数的作用域访问,并且createItem函数使用它没有问题。谁能帮我看看我在这里错过了什么。

// GLOBAL DB VAR
var db;
// WAIT FOR DOM
document.addEventListener("DOMContentLoaded", function(){
    // IF INDEXED DB CAPABLE
    if("indexedDB" in window) {
        // OPEN DB
        var openRequest = indexedDB.open("newTabTest",1);
        // CREATE NEW / UPDATE
        openRequest.onupgradeneeded = function(e) {
            // Notify user here: creating database (first time use)
            var thisDB = e.target.result;
            // Create "items" table if it doesn't already exist
            if(!thisDB.objectStoreNames.contains("items")) {
                var store = thisDB.createObjectStore("items", {keyPath: "id", autoIncrement: true});
                store.createIndex("name","name", {unique:true});
                store.createIndex("folder","folder", {unique:false});
                store.createIndex("dial","dial", {unique:false});
            }
        }
        openRequest.onsuccess = function(e) {
            // Success- set db to target result.
            db = e.target.result;
        }
        openRequest.onerror = function(e) {
            // DB ERROR :-(
        }
    }
},false);

// CREATE ITEM FUNCTION
function createItem(n,u,f,c) {
    var transaction = db.transaction(["items"],"readwrite");
    var store = transaction.objectStore("items");
    var item = {
        name: n,
        url: u,
        folder: f,
        colour: c,
        dial: 0,
        order: 100
    }
    var request = store.add(item);
    request.onerror = function(e) {
        console.log("An error occured.");
    }
    request.onsuccess = function(e) {
        console.log("Successfully added.")
    }
};

// GET ITEM(S) FUNCTION
// Specify index and key value OR omit for all
function getItems(callback, ind, key) {
    var transaction = db.transaction(["items"],"readonly");
    var store = transaction.objectStore("items");
    var response = [];

    // If args are omitted - grab all items
    if(!ind | !key) {
        var cursor = store.openCursor();
        cursor.onsuccess = function(e) {
            var res = e.target.result;
            if(res) {
                var r = {
                    "name": res.value['name'],
                    "url": res.value['url'],
                    "folder": res.value['folder'],
                    "colour": res.value['colour'],
                    "dial": res.value['dial'],
                    "order": res.value['order']
                };
                response.push(r);
                res.continue();
            }
        }
        cursor.oncomplete = function() {
            callback(response);
        }
    } else {
        // If both args are specified query specified index
        store = store.index(ind);
        var range = IDBKeyRange.bound(key, key);
        store.openCursor(range).onsuccess = function(e) {
            var res = e.target.result;
            if(res) {
                var r = {
                    "name": res.value['name'],
                    "url": res.value['url'],
                    "folder": res.value['folder'],
                    "colour": res.value['colour'],
                    "dial": res.value['dial'],
                    "order": res.value['order']
                };
                response.push(r);
                res.continue();
            }
        }
        cursor.oncomplete = function() {
            callback(response);
        }
    }
};

最佳答案

正如您在注释中指出的那样,您确实必须将依赖于db的操作粘贴在从success处理程序调用的函数中。

这种基于回调的编程很快变得很痛苦,为此的常见解决方案是使用promises

但是,使IndexedDB与Promise一起工作仍在进行中(如果您有兴趣,请参见https://github.com/inexorabletash/indexeddb-promises)。

如果您的目标是完成某件事(而不是学习裸露的IndexedDB API),那么也许最好还是找到一个wrapper library for IndexedDB(尽管不建议这样做,因为我尚未尝试与IDB认真合作) )。

关于javascript - 全局变量仅可用于第一个功能?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37127713/

10-17 02:51