IDBTransaction: objectStore() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

注意:此功能在 Web Workers 中可用。

IDBTransaction 接口的 objectStore() 方法会返回一个已经添加到此事务范围内的对象存储空间。

在同一事务对象上,使用相同的名称调用此方法,每次都会返回同一个 IDBObjectStore 实例。如果此方法在不同的事务对象上调用,则会返回一个不同的 IDBObjectStore 实例。

语法

js
objectStore(name)

参数

name

所请求对象存储的名称。

返回值

一个用于访问对象存储的 IDBObjectStore 对象。

异常

NotFoundError DOMException

如果所请求的对象存储不在此事务的范围内,则会抛出此异常。

InvalidStateError DOMException

如果在已删除或移除的源对象上发出请求,或者事务已完成,则会抛出此异常。

示例

在以下代码片段中,我们打开了一个数据库的读/写事务,并向一个对象存储中添加了一些数据。同时,还注意到了附加到事务事件处理程序上的函数,用于在成功或失败时报告事务打开的结果。完整的可运行示例,请参阅我们的 待办事项通知 应用(在线查看示例)。

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.";
  };
}

规范

规范
Indexed Database API 3.0
# ref-for-dom-idbtransaction-objectstore①

浏览器兼容性

另见