【发布时间】:2019-02-25 15:48:22
【问题描述】:
背景
我有一种情况,我想要一些下拉菜单,这些下拉菜单会根据可用的内容更改选项。我已经设法简化了这段代码,并用下面的代码复制了这个问题。
在本例中,我有 5 种可用颜色,我想从中选择四种。如果我选择一个,那么我希望它在其他菜单中不可用。
问题
下拉菜单只是一种工作。根据可用的内容,显示的选项似乎确实有效,但是有时在选择一个条目时,直到我第二次选择它才会允许它。此外,如下面的注释代码所示,lodash _.sortBy 似乎完全破坏了功能。
HTML
<div data-bind="foreach:colorChoices">
<select data-bind="options: localAvailableOptions, optionsCaption: 'Select...', optionsText: function(currentValue) {return 'Color ID ' + currentValue;}, value: id"></select>
</div>
Javascript
function appModel() {
var self = this;
self.colorIds = [1, 2, 3, 4, 5];
self.colorChoices = ko.observableArray();
self.selectedColorIds = ko.computed(function() {
return _(self.colorChoices())
.filter(function(item) {
return item.id()
})
.map(function(item) {
return item.id()
})
.value();
});
self.availableColorIds = ko.computed(function() {
return _.difference(self.colorIds, self.selectedColorIds());
});
self.colorChoices.push(new colorChoice(self));
self.colorChoices.push(new colorChoice(self));
self.colorChoices.push(new colorChoice(self));
self.colorChoices.push(new colorChoice(self));
}
function colorChoice(parent) {
var self = this;
self.id = ko.observable();
self.localAvailableOptions = ko.computed(function() {
//clone as to not modify original array
var availableIds = _.clone(parent.availableColorIds());
//add own ID so dropdown menu contains matching entry
if (self.id()) {
availableIds.push(self.id());
}
//seems to break with _.sortBy
//return _.sortBy(availableIds);
return availableIds;
});
}
ko.applyBindings(new appModel());
CodePen(相同代码)
【问题讨论】:
标签: javascript html knockout.js lodash