【问题标题】:Foreach instead of options binding - replicate “optionsCaption” functionality?Foreach 而不是选项绑定 - 复制“optionsCaption”功能?
【发布时间】:2018-01-08 18:03:50
【问题描述】:

我有这个选择字段:

<select data-bind="foreach: $root.feeGroups, value: $root.selectedFee">
     <optgroup data-bind="attr: {label: label}, foreach: fees">
           <option data-bind="text: description, option: $data"></option>
     </optgroup>
</select>

feesGroup 属性:

 self.feeGroups([
        { label: "NEW", fees: self.fees().filter(f => f.status === "New") },
        { label: "OLD", fees: self.fees().filter(f => f.status === "Old") }
    ]);

还有binding handler

ko.bindingHandlers.option = {
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        console.log(ko.toJSON(value));
        ko.selectExtensions.writeValue(element, value);
    }
};

我的问题与“optionsCaption”有关,因为我正在使用 foreach 方法生成内部选项,如果我能够使用“Options”绑定,它不会像它那样自动工作。但我确实需要一个“请选择...”默认选项。

有办法吗?

【问题讨论】:

  • 能否提供codepen.io中的示例

标签: select knockout.js


【解决方案1】:

您可以将foreach 绑定移动到一个虚拟元素,并在您的视图中添加一个代表null 值的额外选项:

<select data-bind="value: selectedFee">
  <option data-bind="text: 'Select an option', option: null"></option>
  <!-- ko foreach: feeGroups -->
  ...
  <!-- /ko -->
</select>

请记住,当占位符处于活动状态时,selectedFee observable 将包含 null

// From: https://stackoverflow.com/a/11190148/3297291
ko.bindingHandlers.option = {
  update: function(element, valueAccessor) {
    var value = ko.utils.unwrapObservable(valueAccessor());
    ko.selectExtensions.writeValue(element, value);
  }
};

const fees = [
  { type: "old", description: "test1" },
  { type: "old", description: "test2" },
  { type: "new", description: "test3" },
  { type: "new", description: "test4" }
];

const feeGroups = [
  { label: "new", fees: fees.filter(f => f.type === "new") },
  { label: "old", fees: fees.filter(f => f.type === "old") }
];

const selectedFee = ko.observable(null);
selectedFee.subscribe(console.log.bind(console, "new selection:"));

ko.applyBindings({ feeGroups, selectedFee });
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<select data-bind="value: selectedFee">
  <option data-bind="text: 'Select an option', option: null"></option>
  <!-- ko foreach: feeGroups -->
    <optgroup data-bind="attr: {label: label}, foreach: fees">
        <option data-bind="text: description, option: $data"></option>
    </optgroup>
    <!-- /ko -->
</select>

【讨论】:

  • 感谢您的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-04
  • 2018-04-11
  • 1970-01-01
  • 2012-07-14
  • 2020-06-10
相关资源
最近更新 更多