11

我已经看到了多个 JavaScript 示例,createIndex它们在创建 ObjectStore 之后直接定义 ObjectStore 索引,如下所示:

var objectStore = ixDb.createObjectStore(osName, { keyPath: pkName, autoIncrement: autoIncrement });

objectStore.createIndex("name", "name", { unique: false }); 

谁能告诉我你如何createIndex在不打电话的情况下在预先存在的桌子上使用createObjectStore?我想这里真正的问题是如何在不使用的情况下获得对 objectStore 的引用createObjectStore

我尝试了以下几种变体,但没有运气:

var objectStore = window.IDBTransaction.objectStore(ObjectStoreName);
var index = objectStore.createIndex(ixName, fieldName, { unique: unique, multiEntry: multiEntry });
4

2 回答 2

4

您在 期间执行此操作onupgradeneeded,这应该与您首先创建对象存储的位置相同。在那里,您可以执行升级它所需的任何适当操作,例如创建新索引。这是一个例子。

于 2012-07-18T15:43:17.533 回答
3

Chrome 目前不支持 onupgradeneeded 事件。如果您想使用旧的或新的 W3 规范获取对 ObjectStore 的引用,这是一种可能的解决方法,通过使用旧的 setVersion 命令或新的 onupgradeneeded 事件的 onsuccess 事件:

var ixDb; 
var ixDbRequest; 
var ixDbVersionTansaction;

//Check to see if we have a browser that supports IndexedDB
if (window.indexedDB) {

ixDbRequest = window.indexedDB.open(dbName, dbVersion);

//For browsers like chrome that support the old set version method
ixDbRequest.onsuccess = function (e) {

    ixDb = ixDbRequest.result || e.result;

    if (typeof ixDb.setVersion === "function") {

        //Put your version checking logic here 

        if (oldVersion < newVersion) {
            var verRequest = ixDb.setVersion(newVersion);

            verRequest.onerror = function (e) {
                //handling error logic here
            }

            verRequest.onsuccess = function (e) {
                //Get a reference to the version transaction 
                //from the old setVersion method.
                ixDbVersionTansaction = verRequest.result;
                //Create database using function provided by the user. 
                UserFunction();
            }
        }
    }
}; 

ixDbRequest.onupgradeneeded = function (e) {
    //FF uses this event to fire the transaction for upgrades.  
    //All browsers will eventually use this method. Per - W3C Working Draft 24 May 2012
    ixDb = ixDbRequest.result || e.currentTarget.result;

    //Get a reference to the version transaction via the onupgradeneeded event (e)
    ixDbVersionTansaction = e.currentTarget.transaction;

    //Create database using function provided by the user. 
    UserFunction();
};

UserFunction(){
    //ObjectStore is accessed via ixDbVersionTansaction variable 
    // in either instance (transaction..objectStore("ObjectStoreName"))
    var ObjectStore = ixDbVersionTansaction.objectStore("ObjectStoreName");
    var index = ObjectStore.createIndex("ixName", "fieldName");
}
于 2012-07-18T20:53:20.537 回答