在Metro风格应用中保存本地数据

时间:2012-04-30 17:52:00

标签: javascript windows windows-runtime visual-studio-express winjs

我想在Windows 8 metro风格应用程序中创建一个分数机制,并希望使用Windows.Storage.ApplicationData在本地保存该分数。自从我对Visual studio和App构建新手以来,我已经非常困难。

var applicationData = Windows.Storage.ApplicationData.current;

var localSettings = applicationData.localSettings;

// Create a simple setting

localSettings.values["totalPike"] = '0';

// Read data from a simple setting

var totalPike = localSettings.values["totalPike"];

if (!totalPike) {
    // No data
}
else {
    // Access data in value
}

// Delete a simple setting

localSettings.values("totalPike");

这就是Windows处理来自msdn

的app数据的方式
$(document).ready(function () {

        var clicks = 99;

        $("#totalScoreTestButton").click(function () {
            totalPike = totalPike + clicks
            $("#totalScoreTest").text(totalPike);
        });
});

这是我用来将得分添加到当时基本总得分的功能,但每当我关闭应用并再次启动时,都不会保存得分。有人可以帮助我,如果可能的话,请解释一下Metro应用程序如何处理本地数据?

1 个答案:

答案 0 :(得分:7)

例如:

(function () {
"use strict";

WinJS.Namespace.define("PersistenceManager", {
    stateFile: "game_state",

    saveState: function () {
        var state = {
            game_state: game_state,
            level: levelIndex,
            score: SCORE,
            playerLives: player_lives,
            compLives: comp_lives
        };

        WinJS.Application.local.writeText(PersistenceManager.stateFile, JSON.stringify(state));
    },

    loadStateAsync: function () {
        var app = WinJS.Application;

        return app.local.exists(PersistenceManager.stateFile).then(function (exists) {
            if (exists)
                return app.local.readText(PersistenceManager.stateFile).then(function (data) {
                    return JSON.parse(data);
                });
            else return null;
        });
    },

});
})();