我的代码有一些问题,希望您能帮助我。我已经把我的 .open 和所有它的以下代码(unupgradeneede、onsuccess、onerror aso.)放在一个 js 文件中,然后我从另一个 js 文件中调用它。但似乎打开 IndexedDB 和创建对象存储的代码永远不会执行。这是代码
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
contosoData = {
db: null,
useDb: function (successCallback) {
var request = window.indexedDB.open("ContosoData", 2);
request.onsuccess = function (e) {
contosoData.db = request.result;
console.log('indexeddb.success');
successCallback();
};
request.onupgradeneeded = function (e) {
console.log('indexeddb.upgradeneeded');
contosoData.db = e.target.result;
if (contosoData.db.objectStoreNames.contains("bookingStore")) {
contosoData.db.deleteObjectStore("bookingStore");
var bookingStore = contosoData.db.createObjectStore("bookingsStore", { keyPath: "id", autoIncrement: true });
bookingStore.createIndex = ('title', 'title', { unique: false });
bookingstore.createIndex = ('id', 'id', { unique: true });
}
else if (contosoData.db.objectStoreNames.contains("workerStore")) {
contosoData.db.deleteObjectStore("workerStore");
var workerStore = contosoData.db.createObjectStore("workerStore", { keyPath: "employeeNr" });
}
else if (contosoData.db.objectStoreNames.contains("customerStore")) {
contosoData.db.deleteObjectStore("customerStore");
var customerStore = contosoData.db.createObjectStore("customerStore", { keyPath: "orgNr" });
}
var machineStore = contosoData.db.objectStoreNames.contains("machineStore", { keyPath: "machineNr" });
contosoData.db.deleteObjectStore("machineStore");
var machineStore = contosoData.db.createObjectStore("machineStore");
};
request.onerror = function (e) {
console.log('indexeddb.onerror: ' + e);
};
request.onblocked = function (e) {
console.log('indexeddb.locked');
};
}
};
contosoData.useDb(function (db) {
var transaction = contosoData.db.transaction(['bookingsStore'], 'readwrite');
var objectStore = transaction.objectStore('bookingsStore');
console.log(objectStore.name);
});
然后,当我尝试运行它时,当我尝试在另一个 js 文件中创建事务时,我得到一个未定义的事务......我已经检查了我的 js 文件与我打开 IndexedDB 的函数是否已链接以正确的方式和顺序到 html 文件。我还设置了一些断点,看起来 useDb 代码永远不会执行。这是代码
function init() {
contosoData.useDb();
calendar.createCalendar();
}
calendar.createCalendar = function () {
var transaction = contosoData.db.transaction(["bookingStore"], "readwrite");
var bookingStore = transaction.objectStore("bookingStore");
}
有什么我想念的吗?我搜索了它,我试图找到一个解决方案,但到目前为止没有成功......