Search code examples
windows-8winjswindows-8.1

WinJS - How to read the value of an item in a Listview


What is the best or suggested way to get an item from a ListView control in WinJS?

This:

var listView = document.getElementById("listView").winControl;
var item = listView.itemDataSource.itemFromIndex(0);
var name = item._value.data.firstName

Or this:

var listView = document.getElementById("listView").winControl;
var item = listView.itemDataSource._list.getAt(i);
var name = item.firstame

Solution

  • If you query the result of the promise you can read the data of the item:

    var item, name;
    
    listView.itemFromIndex(0).done(function (result) {
    
        if (result) {
    
            item = result;
    
            name = item.data.firstName;
    
        }
    
     }, function() {
    
          //Your error handler here
    
     });
    

    Tip - Both of your examples contain private variables (prefixed with _) - usually a sign that it's not good practice to be accessing these.