2012-10-17 191 views
0

我有一个包含页面上各种元素属性的IndexedDB。我对这些属性之一有一个索引,我使用一个键范围来获得特定的结果列表。等待IDBCursor.onsuccess完成

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(); 
}; 

回答

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'); 
}; 
+0

我最初尝试过这个,但'cursor.oncomplete'永远不会触发(至少在Chrome 23.0.1271.26中) –

+0

游标对象没有完成事件,您应该将此事件绑定到事务对象。 –

+0

我想我不明白...变量'游标'代表事务'openCursor()'...我不知道还有什么我会绑定'oncomplete'函数... –

1

事实证明,cursor.onsuccess火灾最后一次与e.target.result不确定。发生这种情况时,您可以执行回拨功能:

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(); 
}; 
+0

你需要调用cursor.continue()在这里或将光标永远不会前进,你永远也没有机会了“执行代码在这里” – alecf

+0

@alecf良好的渔获!我的确在使用cursor.continue(),我只是忘了将它复制到我的文章中。我现在补充一下。 –