我可以在索引数据库中存储javascript类对象吗?

时间:2018-10-26 12:15:29

标签: javascript class indexeddb

我用构造函数和一些方法创建了一个名为Book的类。

class Book {
    constructor(title, author) {
        this.title = title;
        this.author = author;
    }

    displayInfo() {
        console.log(`Title: ${this.title}, Author: ${this.author}`);
    }
}

然后我创建了一堆Book对象,并将它们放在名为Library的数组中。

const book1 = new Book('Hobbit', 'JRR Tolkien');
const book2 = new Book('Mistborn', 'Brandon Sanderson');

let library = [];
library.push(book1);
library.push(book2);

console.log(library);
library.forEach(book => book.displayInfo());

然后我将此库数组存储在indexeddb中。

if (!window.indexedDB) {
    window.alert("IndexedDB doesn't work");
}

let request = indexedDB.open("Database", 1);
let db, tx, store;
request.onupgradeneeded = function(e) {
let db = request.result;
let store = db.createObjectStore('Collection', { keyPath: 'type' });
};
request.onerror = function(e) {
    console.log('error ' + e.target.errorCode);
};
request.onsuccess = function(e) {
    db = request.result;
    tx = db.transaction('Collection', 'readwrite');
    store = tx.objectStore('Collection');

    db.onerror = function(e) {
        console.log('error ' + e.target.errorCode);
    };
    console.log('adding do collection db');
    store.put({ type: 'library', data: library });

    tx.oncomplete = function() {
        db.close();
    };
};

现在,我想在每次刷新页面后恢复此数组,并对存储在数组中的对象运行Book方法。但是当我恢复数据时,我发现我的Book对象不再是Book对象,而只是常规对象,因此我无法在它们上使用Book方法。

if (!window.indexedDB) {
    window.alert("IndexedDB doesn't work");
}

let request = indexedDB.open("Database", 1);
let db, tx, store;
request.onupgradeneeded = function(e) {
    console.log('upgrading');
    let db = request.result;
    let store = db.createObjectStore('Collection', { keyPath: 'type' });
};
request.onerror = function(e) { console.log('error ' + e.target.errorCode); };
request.onsuccess = function(e) {
    console.log('success');
    db = request.result;
    tx = db.transaction('Collection', 'readwrite');
    store = tx.objectStore('Collection');

    db.onerror = function(e) { console.log('error ' + e.target.errorCode); };

    let retrievedData = store.get('library');

    retrievedData.onsuccess = function(e) {
        if (retrievedData.result) console.log(retrievedData);
        if (retrievedData.result) library = retrievedData.result.data;

        console.log(library);
        library.forEach(book => book.displayInfo());
    }

    tx.oncomplete = function() {
        db.close();
    };
};

有没有解决这个问题的方法?

最好的问候, 奥斯卡

1 个答案:

答案 0 :(得分:1)

这不是一个好习惯,但是在检索库对象之后,您可以尝试:

retrievedData.onsuccess = function(e) {
    if (retrievedData.result) console.log(retrievedData);
    if (retrievedData.result) library = retrievedData.result.data;
    const fixedLibrary = library.map(book => Object.setPrototypeOf(book, Book.prototype))
    fixedLibrary.forEach(book => book.displayInfo());
}

尽管,如果您打算将实例存储在数据库中,我建议您不要使用类,而应使用面向模块的方法...