为什么我的数据库属性在 IndexedDB 中不断被重置?

Why does my database attribute keep getting reset in IndexDB?

我是一名学生,我的任务是使用 IndexedDB 创建一个带有客户端身份验证的待办事项应用程序。

我正在尝试存储帐户数据,但即使在 onupgradeneeded 方法期间工作后,我的数据库属性仍将其自身设置回 null。我一直在使用调试器,它实际上并没有显示我的代码 运行 onupgradeneeded 方法,尽管它在 Firefox 上创建了正确的商店。

任何帮助将不胜感激!

非常感谢

class DatabaseConnection
{
    constructor(name="todoapp", version=1) {
        this.name = name;
        this.version = version;
        this.database = null;

        // Normalise IndexedDB by switching versions depending on browser
        var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

        // If the browser does not support IndexedDB, do not load
        if(!indexedDB) document.write("Your browser does not support IndexedDB. Please try another browser.");
        else console.log(`Database [${name}] successfully loaded.`);

        /* Instead of using anonymous functions in the constructor, I'm going to use private methods in the class
        for organisational and performance purposes */
        var request = indexedDB.open(name, version);
        request.onerror = this._onerror;
        request.onsuccess = this._onsuccess;
        request.onupgradeneeded = this._onupgradeneeded;
    }

    /* Account methods
    =================== */

    registerAccount() {
        console.log(this);
        let tx = this.database.transaction(["accounts"], "readwrite");

        let account = {
            username: "George",
            password: "Test"
        };

        tx.objectStore("accounts").add(account);
    }

    /* Private methods
    =================== */

    _onerror(event) {
        alert("[ERROR] :: " + event.target.error);
    }

    _onsuccess(event) {
        this.database = event.target.result;
    }

    _onupgradeneeded(event) {
        this.database = event.target.result;

        // Defining the data used in the database
        this.database.createObjectStore("todos", {
            keyPath: "id",
            autoIncrement: true
        });
        this.database.createObjectStore("accounts", {
            keyPath: "id",
            autoIncrement: true
        });
    }
}

回调没有“绑定”,因此它们将使用与您预期不同的 this 值调用。

如果您从回调内部执行 console.log(this),您将看到发生了什么,以及为什么 this.database = ... 没有按预期工作。

试试这个:

request.onsuccess = this._onsuccess.bind(this);
request.onupgradeneeded = this._onupgradeneeded.bind(this);

... 将您的函数变成一个自动将 this 设置为您想要的函数。