indexeddb CursorWithValue
是否会在我致电cursor.continue()
之前存储下一条或上一条记录的内容?我可以查看IDBCursorWithValue
对象然后将指针存储到下一条记录吗?
是否可以通过部分密钥获取第一条记录,然后仅当用户点击下一条记录而不缓冲数组中的记录集合时才获取下一条记录?
我知道我可以使用cursor.continue()
获取所有匹配的记录并存储在数组中。我也理解异步,如果我只是取第一个匹配记录,并终止调用数据库的onsuccess
函数终止,我相当确定我失去了链接到下一条记录。
以下工作,我可以获得部分密钥的一个或所有匹配记录。使用\uffff
我基本上可以获得匹配的alpha和所有更大的记录。
storeGet = indexTITLE.openCursor(IDBKeyRange.bound(x.value, x.value, '\uffff'), 'next');
这对我来说是全新的,也许我看这一切都错了。任何建议表示赞赏。我一直在阅读这里的每个帖子和github,我希望其他人已经在使用indexeddb这样做。
答案 0 :(得分:4)
让我试着重述一下这个问题:
你在一个范围内部分迭代了一个游标。现在,您希望在继续之前停止并等待用户输入。但交易将关闭,因此您不能继续点击。你又做了什么?
首先:好问题!这很棘手。你有一些不同的选择。
在最简单的情况下,您有一个唯一索引(或对象存储),因此没有重复的键。
var currentKey = undefined;
// assumes you open a transaction and pass in the index to query
function getNextRecord(index, callback) {
var range;
if (currentKey === undefined) {
range = null; // unbounded
} else {
range = IDBKeyRange.lowerBound(currentKey, true); // exclusive
}
var request = index.openCursor(range);
request.onsuccess = function(e) {
var cursor = request.result;
if (!cursor) {
// no records found/hit end of range
callback();
return;
}
// yay, found a record. remember the key for next time
currentKey = cursor.key;
callback(cursor.value);
};
}
如果你有一个非唯一索引,那么因为你需要存储索引键和主键而更加棘手,并且无法在该位置打开光标。 (请参阅功能请求:https://github.com/w3c/IndexedDB/issues/14)因此,您需要将光标前移到先前看到的key / primaryKey位置:
var currentKey = undefined, primaryKey = undefined;
// assumes you open a transaction and pass in the index to query
function getNextRecord(index, callback) {
var range;
if (currentKey === undefined) {
range = null; // unbounded
} else {
range = IDBKeyRange.lowerBound(currentKey, true); // exclusive
}
var request = index.openCursor(range);
request.onsuccess = function(e) {
var cursor = request.result;
if (!cursor) {
// no records found/hit end of range
callback();
return;
}
if (indexedDB.cmp(cursor.key, currentKey) === 0 &&
indexedDB.cmp(cursor.primaryKey, primaryKey) <= 0) {
// walk over duplicates until we are past where we were last time
cursor.continue();
return;
}
// yay, found a record. remember the keys for next time
currentKey = cursor.key;
primaryKey = cursor.primaryKey;
callback(cursor.value);
};
}
我假设没有上限,例如我们想要索引中的所有记录。您可以根据需要替换range
的初始化。