BrianLegg
BrianLegg

Reputation: 1700

Store and Retrieve WinJS.Binding.List in Application Data

I'm developing a Windows 8 Store app using HTML/JavaScript and I've run into an issue storing and retrieving a WinJS.Binding.List into Windows.Storage.ApplicationData.current.roamingSettings.

I DID get this to work by hand rolling my own method of converting the binding list into XML string and storing that, then on retrieval parsing it back out into a list. But, this seems crazy inefficient and I'm trying to find a better way. I've tried JSON.stringify() and JSON.parse() which seem to store and retrieve the right data but as soon as I bind the data to the winControl the application crashes with a 0 (no error message at all).

Here's a bit of my code to demonstrate what I'm attempting (list is a binding list):

function onSaveData() {
    if (list) {
        Windows.Storage.ApplicationData.current.roamingSettings.values["data"] = JSON.stringify(list);
    }
}

function onLoadData() {
    var data = Windows.Storage.ApplicationData.current.roamingSettings.values["data"];

    if (data) {
        list = JSON.parse(data);
        var listview = element.querySelector("#mylistview").winControl;
        listview.itemsSource = new WinJS.Binding.List(list);
    }
}

I know I can get this working the long way, so I'm not looking for any solution... I'm really just hoping there's an easy way to store/retrieve these data objects that I'm missing. If I can find an easier way to do this it will eliminate about 40 lines of code and I can stop using an entire library. Also, as I go forward I plan to have more binding lists that will need to be stored as well. Thanks!

Upvotes: 0

Views: 505

Answers (1)

You need to bind to the List's dataSource property, not to the List itself:

listview.itemsSource = new WinJS.Binding.List(list).dataSource;

The dataSource property is specifically the IListDataSource that the ListView requires for a data source. The ListView doesn't understand anything about the WinJS.Binding.List directly, only through that particular interface. (I discuss this in Chapter 7, section "The Structure of Data Sources", in my free ebook, Programming Windows Store Apps with HTML, CSS, and JavaScript, 2nd Edition.)

Your saving and reloading the list with JSON is completely fine.

Upvotes: 2

Related Questions