Search code examples
javascriptwindowswindows-runtimevisual-studio-expresswinjs

Saving Local Data in Metro Style App


I want to make a score mechanism in windows 8 metro style app and want to save that score locally using Windows.Storage.ApplicationData i'm having quite a hard time since im new to visual studio and App building.

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

That is how windows handles app data from msdn

$(document).ready(function () {

        var clicks = 99;

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

This is the function i use to add the score to the total score preatty basic at the time but whenever i close the app and start it again no score is saved. Can someone help me in this, and if possible explain me how Metro apps handle local data?


Solution

  • For example:

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