Devlog

Titanium switch in listview item

I was using a listview with rows that had a label and a switch element. The switch element could be turned on or off and new items could be inserted into the listview. When new items where inserted I just replaced all items. This was giving me some nice surprise, as the value of the switch element did not show the value it should show. Seemingly randomly it showed true or false.

This is the template I was using:

<ItemTemplate name="template" class="templateRow">
  <Label class="listViewKeyLabel" bindId="title" />
  <Switch bindId="switchElement" value="false"
    onChange="switchChange" />
</ItemTemplate>

When a created the list, everything went smooth:

function setListItems(myItems) {
  myItems.map(function(item) {
    listItems.push({
      title : { text : item.name },
      switchElement : { value : item.switchValue },
      properties : {
        itemId : item.id
      }
    });
  });
  myListSection.setItems(listItems);
}

But after I replaced this list with new items, the switches were given me wrong values:

// Add some new items and then display them
myItems.push({
  name : "New item",
  switchValue : false
});
setListItems(myItems);

After much trial and error I found the cause and the solution on https://jira.appcelerator.org/browse/TIMOB-16873. Rows are being reused so you have to make sure you update the item after a switch change:

function switchChange(e) {
  var item = e.section.getItemAt(e.itemIndex);
  item.switchElement.value = e.value;
  e.section.updateItemAt(e.itemIndex, item);
}