我正在关注如何进行多选绑定的official tutorial。
我需要限制选择的数量:例如,在具有6个选项的多选中,只能选择2个。有可能吗?
如果我需要做哪些替代方案来实现这样的结果(例如查询,选择2,......)?
答案 0 :(得分:3)
我需要限制选择的数量:例如,在具有6个选项的多选中,只能选择2个。有可能吗?
是的,这很容易。
创建一个包含所选对象的可观察数组。在viewmodel中写入逻辑
ko.computed
- 如canAddMoreItems
- 基于数组长度返回true或false,然后绑定{{ 1}}相应地) - 这是简单的替代方案 - 或以下实现了第二个变体,因为它比第一个更难。
enabled
function MultiSelect(items, limit) {
var self = this,
selection = [];
self.items = items;
self.selectedItems = ko.observableArray();
self.selectedItems.subscribe(function (selectedItems) {
// find out which new items the user selected, add them to our list
ko.utils.arrayForEach(selectedItems, function (item) {
if (ko.utils.arrayIndexOf(selection, item) === -1) {
selection.push(item);
}
});
// find out which items the user de-selected, remove them from our list
ko.utils.arrayForEach(selection, function (item) {
if (ko.utils.arrayIndexOf(selectedItems, item) === -1) {
ko.utils.arrayRemoveItem(selection, item);
}
});
// remove excess items directly from the underlying selectedItems array
if (selectedItems.length > limit) {
self.selectedItems.valueWillMutate();
while (selectedItems.length > limit) {
ko.utils.arrayRemoveItem(selectedItems, selection.shift());
}
self.selectedItems.valueHasMutated();
}
});
}
var vm = new MultiSelect(['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'], 2);
ko.applyBindings(vm);
注意:
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select multiple size="6" data-bind="
options: items,
selectedOptions: selectedItems
"></select>
<hr>
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
辅助变量维护用户单击项目的顺序。这是必要的,因为selection
绑定使所选项保持与源数组(selectedOptions
绑定)中的顺序相同。
不幸的是,这使得无法确定最旧的选项是什么(即当用户选择超过限制时首先抛出的选项)。为了获得流畅的用户体验,最好跟踪用户的行为。
由于用户可以选择其他方式而不是用鼠标单击(拖动鼠标或按住 Ctrl + Shift ,同时使用光标键也可以),代码必须能够处理“变化增量”不止一个项目的情况。
这里解释了options
和valueWillMutate
的小歌舞例程:http://www.knockmeout.net/2012/04/knockoutjs-performance-gotcha.html