为什么这个itemDataSource没有被清除?

时间:2013-01-05 17:44:47

标签: javascript listview winjs itemdatabound

我正在尝试从应用程序中的itemDataSource中删除所有项目。 itemDataSource绑定到listview。

我已经设法在列表视图中点击它时删除了一个项目,但删除所有项目会导致我出现问题:(

这是我用来从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();

这是我试图删除所有项目的代码:

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();

当我运行此代码时,这是我在控制台中获得的输出:

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

为什么只删除部分项?输出是预期的,但导致项1,3,5,7,9, and 11不被删除的原因是什么?我注意到序列中有一个模式,每次都是2。

非常感谢任何帮助:)

1 个答案:

答案 0 :(得分:2)

这是因为您要从列表中删除内容,然后重新编入索引。当您移除项目6时,项目7变为项目6,项目8变为项目7,因此您不删除(原始)项目7,而是删除(原始)项目8。

如果您只删除索引0直到它们没有项目,它应该工作得更好。另请查看列表中的clear()以支持清除它。

此外,我注意到你使用了很多内部状态(带有_前缀的项目) - 你可能要小心那些,因为那些可能会随时改变。

相关问题