简体   繁体   English

使用javascript在Windows Phone 8中进行应用程序设置

[英]Application settings in Windows phone 8, using javascript

I'm developing an app for WP8 using HTML5/JavaScript. 我正在使用HTML5 / JavaScript开发WP8应用程序。 I gather user settings in array variable in JavaScript, and would very much like to save these for future use. 我将用户设置收集在JavaScript的数组变量中,非常希望将其保存以备将来使用。 And save them in roaming settings to be more precise. 并将它们保存在漫游设置中以更精确。

After some research, it seems that this is impossible straight from js. 经过一些研究,似乎从js直接实现是不可能的。 The API calls I found to perform this task in Windows 8 does not work under WP8. 我发现在Windows 8中执行此任务的API调用在WP8下不起作用。 So only work-around I can come up is structure: 所以,唯一可以解决的问题是结构:

1) When I want to save data, from js I make 1)当我想保存数据时,我用js做

window.external.notify("LaunchSaveProcess"); 

to send notification to browser. 向浏览器发送通知。

2) In XAML file 2)在XAML文件中

<phone:WebBrowser ScriptNotify="Catch_Script_Notification" /> 

to deliver notifications from browser to c# 将通知从浏览器传递到C#

3) In c# catch the notification 3)在C#中捕获通知

private void Catch_Script_Notification(object sender, NotifyEventArgs e)
{ if (e.Value.StartsWith("LaunchSaveProcess")) {
            //"important function"
} }

4) The "important function" calls a method in JavaScript, which returns the array of user settings, then proceeds to save the data using 4)“重要函数”调用JavaScript中的方法,该方法返回用户设置的数组,然后继续使用保存数据

var userSettings = Browser.InvokeScript("getSettings()");
var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
roamingSettings.Values["settings"] = userSettings;

Now few questions. 现在几个问题。 Is this model right, or is there a easier way to do it? 这个模型正确吗,或者有更简单的方法吗? Can you pass parameters straight from JavaScript to c# somehow while making notification event? 您可以在进行通知事件时以某种方式将参数直接从JavaScript传递给c#吗? Can I save array straight into roamingSettings, or do I need to chop it down and save everything separate? 我可以将数组直接保存到roamingSettings中,还是需要将其切碎并分别保存?

For clarification the usersettings array is 1-dimensional array, where I push objects with "key" and "value" pairs. 为了明确起见,usersettings数组是一维数组,在这里我将对象以“键”和“值”对进行推送。 So I can easily access content within loop using userSettings[i].key and .value syntax. 因此,我可以使用userSettings [i] .key和.value语法轻松访问循环内的内容。

Windows.Storage.ApplicationData.Current.RoamingSettings is not supported on Windows Phone 8, but is supported in Windows Phone 8.1. Windows Phone 8 不支持 Windows.Storage.ApplicationData.Current.RoamingSettings ,但Windows Phone 8.1支持Windows.Storage.ApplicationData.Current.RoamingSettings Instead, you can just use the Isolated Storage. 相反,您可以只使用隔离存储。

You can use the Coding4Fun.Toolkit.Storage package from NuGet and simply call Serialize.Save("PATH", objectToSave) to save an item and var result = Serialize.Open<TypeOfObject>("PATH") to get the data back. 您可以使用NuGet的Coding4Fun.Toolkit.Storage包,只需调用Serialize.Save("PATH", objectToSave)保存一个项目,然后使用var result = Serialize.Open<TypeOfObject>("PATH")取回数据。

NOTE: Starting with the next release of the toolkit, Serialize will be Serializer . 注意:从工具包的下一个版本开始, Serialize将是Serializer Just an FYI. 仅供参考。

Another alternative to calling back into JavaScript from C# is to pass all the data in your notification string in one go. 从C#回调JavaScript的另一种方法是一次性传递通知字符串中的所有数据。

From your JavaScript side, it is very easy to generate a JSON representation of your data. 从您的JavaScript角度来看,生成数据的JSON表示非常容易。 From the C# side however you would have to declare the DataContract that DataContractJsonSerializer would need to interpret this data, which is a bit more work. 但是,从C#端,您必须声明DataContract, DataContractJsonSerializer将需要解释该数据,这需要做更多工作。

JavaScript helper function which takes in your 1D array of key/value pairs: JavaScript辅助函数,它包含键/值对的一维数组:

function saveUserSettings(valuesToSave) {
    var notifyObject = { command: "saveUserSettings", values: valuesToSave };
    var notifyObjectString = JSON.stringify(notifyObject);
    window.external.notify(notifyObjectString);
}

// call it like this...
saveUserSettings([{ key: "key1", value: "value1" }, 
    { key: "key2", value: "value2" }]);

C# contracts: C#合约:

using System.Runtime.Serialization;

[DataContract]
public class JsonScriptData
{
    [DataMember(Name = "command")]
    public string Command { get; set; }

    [DataMember(Name = "values")]
    public JsonUserSetting[] Values { get; set; }
}

[DataContract]
public class JsonUserSetting
{
    [DataMember(Name = "key")]
    public string Key{ get; set; }

    [DataMember(Name = "value")]
    public object Value { get; set; }
}

and your browser script notify becomes: 并且您的浏览器脚本notify变为:

    private void BrowserOnScriptNotify(object sender, NotifyEventArgs notifyEventArgs)
    {
        var str = notifyEventArgs.Value;
        var serializer = new DataContractJsonSerializer(typeof(JsonScriptData));
        var bytes = Encoding.UTF8.GetBytes(str);

        JsonScriptData commandData;
        using (var memoryStream = new MemoryStream(bytes))
        {
            commandData = (JsonScriptData)serializer.ReadObject(memoryStream);
        }

        // save out to application settings dictionary
        var applicationSettings = IsolatedStorageSettings.ApplicationSettings;
        foreach (var value in commandData.Values)
        {
             applicationSettings[value.Key] = value.Value;
        }
        applicationSettings.Save();
    }

Of course you could save the whole user settings JSON string from JS as a single value into IsolatedStorageSettings which then means C# wouldn't even need to parse it. 当然,您可以将JS中的整个用户设置JSON字符串作为一个值保存到IsolatedStorageSettings中,这意味着C#甚至不需要解析它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM