SAPUI5 jQuery.sap.storage 变量保存

SAPUI5 jQuery.sap.storage variable saving

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

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

之后我需要比较来自函数的变量和来自函数的变量并得到它们的平均值。

我知道存储是键值类型,但我仍然无法完成这项工作。该功能发布在下面。感谢所有可能的帮助。

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

如您所见,我至少已经开始初始化存储了。

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

return 对你来说没什么,对吧?这是因为您在此调用之前没有存储值。此外,我猜你应该使用字符串作为键...

使用 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");

密钥应该是字符串...

正如我在您的其他问题的评论中所说,存储类似于存储键值对的字典。

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

值可以是任何东西:数字、字符串、布尔值、数组、对象,应有尽有。

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,仅支持字符串作为值。我尝试了其他类型,它们都有效,但(反)序列化数据可能是最安全的。我更新了代码示例。