I'm trying to remove all items from an itemDataSource in my application. The itemDataSource is bound to a listview.
I've managed to remove a single item when it's clicked on in a listview, but removing all items is causing me problems :(
This is the code I used to remove a single item from the itemDataSource:
//remove the clicked playlist item
var ds = document.getElementById("PlaylistListView").winControl.itemDataSource;
ds.beginEdits();
ds.remove(ds.itemFromIndex(eventInfo.detail.itemPromise._value.index)._value.key);
ds.endEdits();
And this is the code I've attempted to write to remove all items:
var ds = document.getElementById("PlaylistListView").winControl.itemDataSource;
ds.beginEdits();
console.log(ds._list._keys);
console.log("There are " + ds._list._keys.length + " items in this list");
for (var i = 0; i < ds._list._keys.length; i++) {
ds.remove(ds._list._keys[i]);
console.log("Item: " + ds._list._keys[i] + " has been removed from the list");
}
ds.endEdits();
This is the output I'm getting in the console when I run this code:
1,2,3,4,5,6,7,8,9,10,11
There are 11 items in this list
Item: 2 has been removed from the list
Item: 4 has been removed from the list
Item: 6 has been removed from the list
Item: 8 has been removed from the list
Item: 10 has been removed from the list
Item: undefined has been removed from the list
Why are only some items being removed? The output is as expected, but what's causing item 1,3,5,7,9, and 11
to not be removed? I noticed there's a pattern in the sequence, which is 2 each time.
Any help would be greatly appreciated :)
This is because you are removing things from the list, and then reindexing into it. When you remove item 6, item 7 becomes item 6, and item 8 becomes item 7, so you don't remove your (original) item 7, you remove (original) item 8 instead.
If you just remove index 0 until their are no items, it should work much better. Also look at the clear() on the list to support clearing it.
Additionally, I noticed you're using lots of internal state (_-prefixed items) -- you might want to be careful there, 'cause those could change at any time.