本文介绍了从 WinJS.Binding.List 中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了 Controls_ListViewWorkingWithDataSources MSDN 示例以了解如何从 WinJS.Binding.List 中删除项目,这是他们的解决方案.请告诉我有更简单的方法.

I looked at the Controls_ListViewWorkingWithDataSources MSDN sample to see how to remove an item from a WinJS.Binding.List and here's their solution. Please tell me there's an easier way.

if (list2.selection.count() > 0) {
    list2.selection.getItems().done(function (items) {

        //Sort the selection to ensure its in index order
        items.sort(function CompareForSort(item1, item2) {
            var first = item1.index, second = item2.index;
            if (first === second) {
                return 0;
            }
            else if (first < second) {
                return -1;
            }
            else {
                return 1;
            }
        });

        //Work backwards as the removal will affect the indices of subsequent items
        for (var j = items.length - 1; j >= 0; j--) {
            // To remove the items, call splice on the list, passing in a count and no replacements
            lettersList.splice(items[j].index, 1);
        }
    });

推荐答案

您可以使用以下方法避免 getItems() 调用和 then 阻塞:iSelection.getIndices();. 为您提供一个包含您需要的索引的数组删除.

You can avoid the getItems() call and the then block by using:iSelection.getIndices();. This gives you an array with the indices you need to remove.

所以代码会更像这样.尚未对此进行测试.

So the code would be more like this. Haven't tested this.

// nothing in docs guarantees these are returned in sorted order, so we need to sort
var indicesList = list2.selection.getindices().sort(function(a,b){return a-b}); 
for (var j = indicesList .length - 1; j >= 0; j--) {
    // To remove the items, call splice on the list, passing in a count and no replacements
    lettersList.splice(indicesList[j], 1);
}

将其封装成一个实用的类,如下所示:

Encapsulate it into a utily class like this:

function deleteSelectedItemsFromList(selection, list) {
    var indicesList = selection.getIndices().sort(function(a,b){return a-b}); 
    for (var j = indicesList .length - 1; j >= 0; j--) {
        // To remove the items, call splice on the list, passing in a count and no replacements
        list.splice(indicesList[j], 1);
    }
}

这样调用:

Utils.deletedSelectedItemsFromList(listview.selection, listViewList);

Bam,你有一个单衬.

Bam, you've got a one liner.

这篇关于从 WinJS.Binding.List 中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 00:58