如何获取具有最高时间戳值的x对象?

时间:2015-06-25 10:07:48

标签: javascript indexeddb

我是网络应用程序开发的新手,我无法找到解决以下问题的方法。基本上我试图从IndexedDB数据库中对最新对象的数组进行排序。每个对象都包含一个时间戳值。我在时间戳上创建了一个索引,并且我能够获得具有最高值的对象。

    function getMails (numberOfMessages, _function) {
/*  This function uses asynchronous methods, hence you have to pass the key and function that will receive
    the messageitem as a parametr */

    if (typeof optionalArg === 'undefined') {
     optionalArg = 10;
    }
    function _getMails (db) {
        var transaction = db.transaction(["MessageItem"], "readonly");
        var store = transaction.objectStore("MessageItem");

        var index = store.index("timestamp");
        var cursor = index.openCursor(null, 'prev');
        var maxTimestampObject = null;

        cursor.onsuccess = function(e) {
            if (e.target.result) {
                maxTimestampObject = e.target.result.value;
                _function(maxTimestampObject);
            }
        };

    }
    openDB(_getMails);
}

函数openDB打开数据库并将db对象作为参数传递给_getMails函数。函数getMails当前仅传递具有最高时间戳值的对象。我可以迭代数据库x(numberOfMessages)次,并且总是选择具有最高时间戳的对象,同时排除已经在我试图获得的数组中的对象。但我不确定这是否是最便捷的方式。谢谢你的回复。扬

2 个答案:

答案 0 :(得分:0)

您只需在// <Name>Complex methods poorly covered by tests</Name> warnif count > 0 from m in Application.Methods where m.CyclomaticComplexity > 10 && m.PercentageCoverage < 20 select new { m, m.CyclomaticComplexity, m.PercentageCoverage, m.NbLinesOfCode } 函数中调用cursor.continue()即可。将使用下一个游标结果再次调用它。

答案 1 :(得分:0)

谢谢Kyaw Tun。以下是我感兴趣的人的最终代码:

function openDB(_function) {
// Opening the DB
var openRequest = indexedDB.open("TsunamiDB",1);
openRequest.onupgradeneeded = function(e) {
    console.log("Upgrading...");
    var thisDB = e.target.result;

    if (!thisDB.objectStoreNames.contains("MessageItem")) {
        var objectStore = thisDB.createObjectStore("MessageItem");
        objectStore.createIndex("timestamp", "envelope.timestamp", {unique:false});
    }
}

openRequest.onsuccess = function(e) {
    console.log("Success!");
    _function(e.target.result);
}

openRequest.onerror = function(e) {
    console.log("Error");
    console.dir(e);
}}

此函数使用异步方法,因此您必须传递将接收messageitem作为参数的键和函数。 Pareametr是x(numberOfMessages)最新消息的数组。对数组进行排序,使索引为0的消息为最新消息。

function getMails ( _function, numberOfMessages) {

if (typeof numberOfMessages === 'undefined') {
 numberOfMessages = 10;
}
function _getMails (db) {
    var transaction = db.transaction(["MessageItem"], "readonly");
    var store = transaction.objectStore("MessageItem");

    var index = store.index("timestamp");
    var objectsArray = [];
    var i = 0;

    index.openCursor(null, 'prev').onsuccess = function(e) {
        var cursor = e.target.result;
        if (cursor && i < numberOfMessages) {
            objectsArray.push(cursor.value)
            ++i;
            cursor.continue();
        }
    };
    transaction.oncomplete = function(e) {
        _function(objectsArray);
    }

}
openDB(_getMails);}
相关问题