IDBDatabase: versionchange 事件
当数据库结构发生更改时,会触发 versionchange
事件 (upgradeneeded
事件发送到 IDBOpenDBRequest
或 IDBFactory.deleteDatabase
) 被请求到其他地方(很可能是在同一台计算机上的另一个窗口/选项卡中)。
语法
在像 addEventListener()
这样的方法中使用事件名称,或者设置事件处理程序属性。
js
addEventListener("versionchange", (event) => {});
onversionchange = (event) => {};
事件类型
一个通用的 Event
。
示例
此示例打开一个数据库,并在成功后添加一个监听器到 versionchange
js
// Open the database
const dBOpenRequest = window.indexedDB.open("Nonexistent", 4);
dBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
dBOpenRequest.addEventListener("success", (event) => {
const db = event.target.result;
db.addEventListener("versionchange", (event) => {
console.log("The version of this database has changed");
});
});
使用 onversionchange
事件处理程序属性的相同示例
js
// Open the database
const dBOpenRequest = window.indexedDB.open("Nonexistent", 4);
dBOpenRequest.onupgradeneeded = (event) => {
const db = event.target.result;
// Create an objectStore for this database
const objectStore = db.createObjectStore("toDoList", {
keyPath: "taskTitle",
});
// define what data items the objectStore will contain
objectStore.createIndex("hours", "hours", { unique: false });
objectStore.createIndex("minutes", "minutes", { unique: false });
objectStore.createIndex("day", "day", { unique: false });
objectStore.createIndex("month", "month", { unique: false });
objectStore.createIndex("year", "year", { unique: false });
};
dBOpenRequest.onsuccess = (event) => {
const db = event.target.result;
db.onversionchange = (event) => {
console.log("The version of this database has changed");
};
};
浏览器兼容性
BCD 表格只在浏览器中加载