SAPUI5 jQuery.sap.storage变量保存

SAPUI5 jQuery.sap.storage variable saving

本文关键字:变量 保存 storage sap jQuery SAPUI5      更新时间:2023-09-26

在我的应用程序中,我有一个同步功能,在该功能中,我在开始和结束时使用两个时间戳来获取同步所花费的时间。

我想把这个变量保存到本地存储器中。

之后,我需要将来自函数的变量与来自函数的参数进行比较,并得到它们的平均值。

我知道存储是一种关键价值类型,我在完成这项工作时仍然存在问题。该函数发布在下面。感谢您的一切帮助。

handleSyncPress: function() {
    new Date().getTime();
    var syncStart = Math.floor(Date.now() / 1000);
    var that = this;
    var fUpdateBindings = function() {
        that.getView().getModel().refresh(true);
    }
    test.mp.Offline.sync(fUpdateBindings);
    new Date().getTime();
    var syncEnd = Math.floor(Date.now() / 1000);
    var syncTime = syncEnd - syncStart;
    this._oStorage = jQuery.sap.storage(jQuery.sap.storage.Type.local);
    this._oMyData = this._oStorage.get(syncTime);
    this._oStorage.put(syncTime, this._oMyData);
}

正如你所看到的,我至少已经开始初始化存储了。

正如我在另一个问题的评论中所说,存储器就像一个存储键值对的字典。

密钥是稍后用于访问您的值的标识符。

这个值可以是任何东西:数字,字符串,布尔,数组,对象,你能想到的

Imo最好的解决方案是将所有同步时间存储在一个值中(即一个同步时间数组)。

handleSyncPress: function() {
    // get current timestamp
    var syncStart = Date.now();
    // do stuff
    var fUpdateBindings = function() {
        that.getView().getModel().refresh(true);
    }
    test.mp.Offline.sync(fUpdateBindings);
    // get another timestamp
    var syncEnd = Date.now();
    // diff between the timestamps is the sync time (in milliseconds)
    var syncTimeInMilliseconds = syncEnd - syncStart;
    this._oStorage = jQuery.sap.storage(jQuery.sap.storage.Type.local);
    // load value for the key "syncTimes"
    var aSyncTimes = this._oStorage.get("syncTimes");
    aSyncTimes = JSON.parse(aSyncTimes); // may not be needed
    // if this is the first time you access the key, initialize the value
    if (aSyncTimes === null) {
        aSyncTimes = [];
    }
    // append your new sync time
    aSyncTimes.push(syncTimeInMilliseconds);
    // store your sync time array
    aSyncTimes = JSON.stringify(aSyncTimes); // may not be needed
    this._oStorage.put("syncTimes", aSyncTimes);
    // hopefully you already know how to calculate the avg value from an array of integers
    // if not: avg = sum / length
}

编辑:根据API,仅支持字符串作为值。我尝试了其他类型,它们都有效,但(反)序列化数据可能是最安全的。我更新了代码示例。

this._oMyData =this._oStorage.get(syncTime);

在你的情况下不会有任何回报,对吧?这是因为您在此调用之前没有存储值。此外,我想您应该使用字符串作为关键字。。。

使用SAPUI5访问localStorage的工作方式如下:

// get an instance of  jQuery.sap.storage.Storage
var oStorage = jQuery.sap.storage(jQuery.sap.storage.Type.local);
//...
// Store
var syncTime = ...;
oStorage.put("syncTime", syncTime);
// Read 
var syncTime = oStorage.get("syncTime");

然而,我更喜欢使用本机JavaScript API,即参见http://www.w3schools.com/html/html5_webstorage.asp:

// Store
var syncTime = ...;
localStorage.setItem("syncTime", syncTime);
// read
var syncTime = localStorage.getItem("syncTime");

密钥应该是字符串。。。