Question

In WinJS the only way to get the count of items in a ListView object is with the method getCount().

But this method is asynchronous.

This make it very difficult to be used in a for loop for example when there is a need to loop through the items of the list.

var listView = document.getElementById("listView").winControl;
listView.itemDataSource.getCount().done(
    function (numItems) {
        for (var i = 0; i < numItems; i++) {
            //do your stuff here
        }
    });

If I put this in any part of my code I can't return the value I read in the loop from any function because the getCount() return a promise, making my function also return a promise and so on...

So my question is why? Isn't the number of items in a list already known when the method is called?

Was it helpful?

Solution 2

The ListView's data contract allows for asynchronous data sources, and we include a base class VirtualizedDataSource that you can use for fancy scenarios like that. If you are using a WinJS.Binding.List as your data source that API is in fact synchronous and you should be able to say:

listView.itemDataSource.list.length

However, if you're writing generic code that deals with ListView's and doesn't know what kind of data source it will

OTHER TIPS

Have you tried joining promises? If your concern is to iterate all of the items in a ListView by selecting each item by index and then performing some work on them, you can use WinJS.Promise.join to create a single promise that contains the results of all the operations.

For example:

var listView = document.getElementById("listView").winControl;
listView.itemDataSource.getCount().then(
    function (numItems) {
        var joinedPromises = [];
        for (var i = 0; i < numItems; i++) {
            joinedPromises.push(listView.itemDataSource.itemsFromIndex(i, 0, 0));
        }
        return WinJS.Promises.join(joinedPromises);
    }).done(
    function (results) {
        // Operate on each item in the ListView's data source.
    },
    function (err) { 
        // Handle any errors from the joined promises.
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top