IDBRequest: transaction 屬性
注意:此功能在 Web Workers 中可用。
IDBRequest 介面的只讀屬性 transaction 返回請求的事務,即該請求是在哪個事務中發出的。
對於不在事務中發出的請求,此屬性可能為 null,例如來自 IDBFactory.open 的請求 — 在這種情況下,您只是連線到資料庫,沒有要返回的事務。如果在開啟資料庫時需要進行版本升級,那麼在 upgradeneeded 事件處理程式期間,transaction 屬性將是一個 IDBTransaction,其 mode 等於 "versionchange",可用於訪問現有的物件儲存和索引,或中止升級。升級完成後,transaction 屬性將再次為 null。
值
一個 IDBTransaction 物件。
示例
以下示例請求一個給定的記錄標題,在 onsuccess 中從 IDBObjectStore(可在 objectStoreTitleRequest.result 中獲得)獲取相關記錄,更新記錄的一個屬性,然後透過另一個請求將更新後的記錄放回物件儲存中。請求的來源被記錄到開發者控制檯 — 兩者都源自同一個事務。有關完整的可用示例,請參閱我們的 待辦事項通知 應用(即時檢視示例)。
js
const title = "Walk dog";
// Open up a transaction as usual
const objectStore = db
.transaction(["toDoList"], "readwrite")
.objectStore("toDoList");
// Get the to-do list object that has this title as its title
const objectStoreTitleRequest = objectStore.get(title);
objectStoreTitleRequest.onsuccess = () => {
// Grab the data object returned as the result
const data = objectStoreTitleRequest.result;
// Update the notified value in the object to "yes"
data.notified = "yes";
// Create another request that inserts the item back
// into the database
const updateTitleRequest = objectStore.put(data);
// Log the transaction that originated this request
console.log(
`The transaction that originated this request is ${updateTitleRequest.transaction}`,
);
// When this new request succeeds, run the displayData()
// function again to update the display
updateTitleRequest.onsuccess = () => {
displayData();
};
};
此示例演示瞭如何在版本升級期間使用 transaction 屬性來訪問現有物件儲存。
js
const openRequest = indexedDB.open("db", 2);
console.log(openRequest.transaction); // Will log "null".
openRequest.onupgradeneeded = (event) => {
console.log(openRequest.transaction.mode); // Will log "versionchange".
const db = openRequest.result;
if (event.oldVersion < 1) {
// New database, create "books" object store.
db.createObjectStore("books");
}
if (event.oldVersion < 2) {
// Upgrading from v1 database: add index on "title" to "books" store.
const bookStore = openRequest.transaction.objectStore("books");
bookStore.createIndex("by_title", "title");
}
};
openRequest.onsuccess = () => {
console.log(openRequest.transaction); // Will log "null".
};
規範
| 規範 |
|---|
| Indexed Database API 3.0 # ref-for-dom-idbrequest-transaction① |
瀏覽器相容性
載入中…
另見
- 使用 IndexedDB
- 開始事務:
IDBDatabase - 使用事務:
IDBTransaction - 設定鍵的範圍:
IDBKeyRange - 檢索和修改資料:
IDBObjectStore - 使用遊標:
IDBCursor - 參考示例:待辦事項通知(檢視即時示例)。