我正在尝试在剔除js中绑定下拉列表,但是在我的数据中有一些副本,是否可以在绑定到下拉列表时删除这些副本?
下面是我如何绑定数据
<select data-bind="options: availableCountries,
optionsText: function(item) {
return item.countryName + ' (pop: ' + item.countryPopulation + ')'
},
value: selectedCountry,
optionsCaption: 'Choose...'"></select>
var Country = function(name, population) {
this.countryName = name;
this.countryPopulation = population;
};我的视图模型如下
var AppViewModel = function() {
this.availableCountries = ko.observableArray([
new Country("UK", 65000000),
new Country("USA", 320000000),
new Country("Sweden", 29000000),
new Country("Sweden", 29000000)
]);
this.selectedCountry = ko.observable();
};
ko.applyBindings(new AppViewModel());这是js小提琴http://jsfiddle.net/PV7yD/
谢谢,
普拉文。
发布于 2014-04-09 14:15:22
您可以在计算的可观察性中使用下划线的_.uniq函数,并使用迭代器将每个项序列化为JSON以进行完全比较。如下所示:
this.displayedCountries = ko.computed( function () {
return _.uniq( this.availableCountries(), false, ko.toJSON );
}, this );您可以用一个函数替换ko.toJSON,该函数只返回一个国家的countryName属性,如果这足以确定唯一性(在本例中可能是这样)。
发布于 2014-04-09 13:59:26
您可以使用ko.utils.arrayGetDistinctValues函数获得不同的值,也可以使用筛选器。
self.uniqueCountries = ko.dependentObservable(function () {
var seen = [];
return self.availableCountries().filter(function (n) {
return seen.indexOf(n.countryName+'-'+n.countryPopulation) == -1 && seen.push(n.countryName+'-'+n.countryPopulation);
});
}, self);意见:-
<select data-bind="options: uniqueCountries,
optionsText: function(item) {
return item.countryName + ' (pop: ' + item.countryPopulation + ')'
},
value: selectedCountry,
optionsCaption: 'Choose...'"></select>欲知更多信息:-
https://stackoverflow.com/questions/22964485
复制相似问题