0

我有一个 IndexedDB,其中包含页面上各种元素的属性。我在其中一个属性上有一个索引,我使用一个键范围来获取特定的结果列表。

var key = IDBKeyRange.bound(10, 20);
var cursor = store.index('property').openCursor(key);

我遇到的问题是cursor.onsuccess功能。它似乎为结果集中的每个结果执行。因此,一旦解析了所有结果,我就无法执行回调函数。

cursor.onsuccess = function (e) {
    var cursor = e.target.result;
    if (cursor) {
        if (cursor.value.prop1 > 30 && cursor.value.prop2 < 80) {
            // Do stuff with result
            someArray.push({
                prop1: cursor.value.prop1,
                prop2: cursor.value.prop2
            }):
        }
    }
    cursor.continue();
};
4

2 回答 2

1

事实证明,cursor.onsuccess最后一次以e.target.resultundefined 触发。发生这种情况时,您可以执行回调函数:

cursor.onsuccess = function (e) {
    var cursor = e.target.result;
    if (cursor) {
        if (cursor.value.prop1 > 30 && cursor.value.prop2 < 80) {
            // Do stuff with result
            someArray.push({
                prop1: cursor.value.prop1,
                prop2: cursor.value.prop2
            }):
        }
    } else {
        // Execute code here
        console.log('There are ' + someArray.length + ' elements in someArray.');
    }
    cursor.continue();
};
于 2012-10-17T20:40:58.013 回答
1

知道您的操作已完成的最安全方法是在完成事件时使用事务。该事件在光标关闭后触发。

transaction.oncomplete = function (event) {
    console.log('transaction completed');
};

还要确保没有发生错误,将事件侦听器添加到错误和中止的事务事件中。

transaction.onerror = function (event) {
    console.log('transaction error');
};

transaction.onabort = function (event) {
    console.log('transaction abort');
};
于 2012-10-18T13:43:22.687 回答