IDBTransaction:complete 事件

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

當事務成功提交時,會觸發 IndexedDB API 的 complete 事件,這可能是在你明確呼叫 IDBTransaction.commit() 之後,或者是在所有請求都成功完成且處理完結果後沒有放置新的請求時發生。有關更多資訊,請參閱 IDBTransaction

語法

在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。

js
addEventListener("complete", (event) => { })

oncomplete = (event) => { }

事件型別

一個通用的 Event

示例

使用 addEventListener()

js
// Open the database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onupgradeneeded = (event) => {
  const db = event.target.result;

  db.onerror = () => {
    console.log("Error creating database");
  };

  // 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 = DBOpenRequest.result;

  // open a read/write db transaction, ready for adding the data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // add a listener for `complete`
  transaction.addEventListener("complete", (event) => {
    console.log("Transaction was completed");
  });

  const objectStore = transaction.objectStore("toDoList");
  const newItem = {
    taskTitle: "my task",
    hours: 10,
    minutes: 10,
    day: 10,
    month: "January",
    year: 2019,
  };
  const objectStoreRequest = objectStore.add(newItem);

  objectStoreRequest.onsuccess = () => {
    // Issue a second request in the onsuccess handler,
    // so we can run this request after the first one completes,
    // while still reusing the same transaction
    const getAllRequest = objectStore.getAll();

    getAllRequest.onsuccess = () => {
      // No more requests, so the transaction completes after running this handler
      console.log(getAllRequest.result);
    };
  };
};

規範

規範
Indexed Database API 3.0
# eventdef-idbtransaction-complete

瀏覽器相容性

另見