2011-03-02 207 views
6

我有一个IndexedDB数据存储,其中包含几百个对象。我想根据该商店的其中一个索引中的顺序从其中获取项目40-59。有没有办法做到这一点,而无需在开始使用数据之前简单地调用cursor.continue()39次?就处理时间而言,这看起来很浪费。使用IndexedDB光标进行分页

回答

6

我有同样的问题,cursor.advance(40)是您要使用的东西。

有一件事花了我一段时间才弄清楚对其他人可能会有用的是,如果你想推进光标并遍历结果,你将需要在单独的openCursor().onsuccess处理程序中调用它们,或者实现某种跟踪以防止它们在相同的请求中被调用或者抛出异常。这是可以做到像这样:

不同的处理器

// advance first 
store.openCursor().onsuccess = function(event) { 
    var cursor = event.target.result; 
    cursor.advance(40); 
}; 

// then iterate 
objectStore.openCursor().onsuccess = function(event) { 
    var cursor = event.target.result; 
    cursor.continue(); 
}); 

相同的处理

// create flag for advancing 
var advancing = true; 

store.openCursor().onsuccess = function(event) { 

    var cursor = event.target.result; 

    // advancing 
    if (advancing === true) { 

     cursor.advance(40); 

     // set advancing flag to false so we don't advance again 
     advancing = false; 

    } 
    // continuing 
    else { 

     cursor.continue(); 

    } 

} 

规格参考:http://www.w3.org/TR/IndexedDB/#widl-IDBCursor-advance-void-unsigned-long-count MDN参考与例如:https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor.advance