代码之家  ›  专栏  ›  技术社区  ›  user3378165

Foreach而不是选项绑定-复制选项标题功能?

  •  0
  • user3378165  · 技术社区  · 7 年前

    我有这个选择字段:

    <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);
        }
    };
    

    我的问题是“optionscomption”,因为我使用foreach方法生成内部选项,它不会像我能够使用“options”绑定那样自动工作。但我需要一个“请选择…”默认选项。

    有办法吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   user3297291    7 年前

    您可以移动 foreach 绑定到虚拟元素,并在视图中添加表示 null 值:

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

    请记住 selectedFee 可观察的将包含 无效的 占位符处于活动状态时。

    // 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>