选择的元素无法使用淘汰赛

时间:2019-02-25 15:48:22

标签: javascript html knockout.js lodash

背景

我遇到一种情况,我希望有一些下拉菜单,这些菜单会根据可用选项来更改选项。我已经设法简化了这段代码,并使用下面的代码复制了该问题。

在此示例中,我有5种可用颜色,我想选择其中四种。如果我选择一个,那么我希望它在其他菜单中不可用。

问题

下拉菜单仅能正常工作。根据可用的内容,显示的选项似乎确实有效,但是有时在选择一个条目时,直到我第二次选择时,它才允许它。另外,如下面的注释代码所示,破折号_.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(相同代码)

https://codepen.io/anon/pen/KEKPKV

1 个答案:

答案 0 :(得分:0)

我找到了问题。

if (self.id()) {
    availableIds.push(self.id());
}

这错过了检查是否已经存在的检查,这意味着可用选项包括重复值,这大概会产生未定义的行为。