IDBTransaction:mode 属性
注意:此功能在Web Workers中可用。
mode
是IDBTransaction
接口的只读属性,它返回在事务范围内访问对象存储中的数据的当前模式(即,模式是只读还是允许写入对象存储?)。默认值为readonly
。
值
一个定义了隔离对当前对象存储中的数据访问模式的对象:一个字符串,定义了隔离对当前对象存储中数据访问的模式。以下值可用
readonly
-
允许读取数据,但不允许更改数据。
readwrite
-
允许读取和写入数据,并允许更改现有数据存储中的数据。
versionchange
-
允许任何操作,包括删除和创建对象存储和索引的操作。此模式用于在调用
IDBFactory.open()
时检测到需要更新事务版本号时。此模式的事务不能与其他事务同时运行。此模式下的事务称为升级事务。
示例
在以下代码片段中,我们在数据库上打开了一个读写事务,并在对象存储中添加了一些数据。另请注意附加到事务事件处理程序的功能,以在事务成功或失败打开的情况下报告事务的结果。最后,我们使用mode
记录当前事务的模式。有关完整的示例,请参阅我们的待办事项通知应用程序(查看示例)。
js
const note = document.getElementById("notifications");
// an instance of a db object for us to store the IDB data in
let db;
// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);
DBOpenRequest.onsuccess = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Database initialized.";
// store the result of opening the database in the db variable.
// This is used a lot below
db = DBOpenRequest.result;
// Run the addData() function to add the data to the database
addData();
};
function addData() {
// Create a new object ready for being inserted into the IDB
const newItem = [
{
taskTitle: "Walk dog",
hours: 19,
minutes: 30,
day: 24,
month: "December",
year: 2013,
notified: "no",
},
];
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["toDoList"], "readwrite");
// report on the success of opening the transaction
transaction.oncomplete = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction completed: database modification finished.";
};
transaction.onerror = (event) => {
note.appendChild(document.createElement("li")).textContent =
"Transaction not opened due to error. Duplicate items not allowed.";
};
// create an object store on the transaction
const objectStore = transaction.objectStore("toDoList");
// add our newItem object to the object store
const objectStoreRequest = objectStore.add(newItem[0]);
objectStoreRequest.onsuccess = (event) => {
// report the success of the request (this does not mean the item
// has been stored successfully in the DB - for that you need transaction.onsuccess)
note.appendChild(document.createElement("li")).textContent =
"Request successful.";
};
// Return the mode this transaction has been opened in (should be "readwrite" in this case)
transaction.mode;
}
规范
规范 |
---|
Indexed Database API 3.0 # ref-for-dom-idbtransaction-mode① |
浏览器兼容性
BCD 表格仅在启用了 JavaScript 的浏览器中加载。
另请参阅
- 使用 IndexedDB
- 启动事务:
IDBDatabase
- 使用事务:
IDBTransaction
- 设置键范围:
IDBKeyRange
- 检索和更改您的数据:
IDBObjectStore
- 使用游标:
IDBCursor
- 参考示例:待办事项通知(查看示例)。