Search code examples
windows-8winjswindows-store

WinJS - Adding 'selected' style to first item in listview on load


I'm trying at present to use a listview to drive the content of a separate div in a Windows Store app (HTML/JS).

I have a simple function which I call inside the 'oniteminvoked' handler for my listview.

Method call

MyApp.Util.addClassById(q(".item"), item.itemId, "selected");

(Where item.itemId is that of my newly selected item and 'q' is an alias for WinJS.Utilities.query)

Method declaration

function addClassById(elements, selectedId, className) {

    elements.forEach(function (el) {

        var id = parseInt(el.attributes['data-id'].value, 10);

        if (id === selectedId) {
            util.addClass(el, className);
        }
        else {
            util.removeClass(el, className);
        }
    });
}

This works as expected after my listview is loaded and I'm selecting new items. Where it doesn't load is when I try to call it during my ready function for the page in question.

When I go through in debug, it seems that my query for items in the list doesn't return anything during the pages ready function, so I'm assuming the list hasn't been rendered at this point and the DOM query returns nothing.

So the question is this, what's the recommended approach to select an item (or perform an action on a listview) after it's been rendered?

I thought they might be an 'afterrender' type event where I could call the function but I can't seem to find anything that works.

Any ideas?


Solution

  • The best way I know of to do this is to capture the onloadingstatechanged event and wait until the ListView has been "loaded". You can see how by visiting my blog post at http://codefoster.com/loadingstates