1

想要从 KoObservableArray 中删除重复值。我有以下 JS 文件。我想将 UI 中的名称列绑定为下拉列表以及删除重复值。

建议最好的方法来做同样的事情。

JS文件

$(function () {
    var initialData = [
    { name: "Well-Travelled Kitten", sales: 352, price: 75.95 },
    { name: "Speedy Coyote", sales: 89, price: 190.00 },
    { name: "Furious Lizard", sales: 152, price: 25.00 },
    { name: "Furious Lizard", sales: 213, price: 25.00 },
    { name: "Indifferent Monkey", sales: 1, price: 99.95 },
    { name: "Speedy Coyote", sales: 89, price: 190.00 },
    { name: "Brooding Dragon", sales: 0, price: 6350 },
    { name: "Ingenious Tadpole", sales: 39450, price: 0.35 },
    { name: "Optimistic Snail", sales: 420, price: 1.50 }
];

    var PagedGridModel = function (items) {
        this.items = ko.observableArray(items);       
    };

    ko.applyBindings(new PagedGridModel(initialData));
});

HTML File 
<body>

<nav>
<label for="name">Name</label>
        <select id="name" data-bind="options: items, optionsText: 'name', optionsCaption:'All'">
        </select>
</nav>

</body>

以上给了我重复名称的下拉列表。

4

1 回答 1

3

请参阅下面的示例,了解如何让计算出的 observable 返回一个数组。我刚刚写下了过滤的逻辑,但它可能不正确或最优,我会留给你改进它。

$(function () {
    var initialData = [
    { name: "Well-Travelled Kitten", sales: 352, price: 75.95 },
    { name: "Speedy Coyote", sales: 89, price: 190.00 },
    { name: "Furious Lizard", sales: 152, price: 25.00 },
    { name: "Furious Lizard", sales: 213, price: 25.00 },
    { name: "Indifferent Monkey", sales: 1, price: 99.95 },
    { name: "Speedy Coyote", sales: 89, price: 190.00 },
    { name: "Brooding Dragon", sales: 0, price: 6350 },
    { name: "Ingenious Tadpole", sales: 39450, price: 0.35 },
    { name: "Optimistic Snail", sales: 420, price: 1.50 }
];

    var PagedGridModel = function (items) {
        var self = this;
        self.items = ko.observableArray(items);       
        self.uniqueItems = ko.computed({
            var filteredArray = [];
            var i;
            $.each(self.items(), function (index, item) {
                 bool alreadyAdded = false;
                 for (i in filteredArray) {
                      if (filteredArray[i].name == item.name) {
                            alreadyAdded = true;
                      }
                 }
                  if (!alreadyAdded) {
                       filteredArray.push(item);
                  }
            });
            return  filteredArray;
        });
    };

    ko.applyBindings(new PagedGridModel(initialData));
});

最后在您的 HTML 中

<select id="name" data-bind="options: uniqueItems, optionsText: 'name', optionsCaption:'All'">
</select>
于 2012-12-21T06:58:43.190 回答