【问题标题】:Construct a knockout SELECT with optgroup based on observableArray基于 observableArray 构造带有 optgroup 的淘汰赛 SELECT
【发布时间】:2013-04-11 12:19:53
【问题描述】:

我开发了一个淘汰赛项目。我找到了一种使用淘汰赛绑定和 optgroup 进行选择的方法。这是解决方案:http://jsfiddle.net/HPhmB/3/

不幸的是,此解决方案使用静态模型在选择中填充“选项”和“选择组”。

出于我个人的需要,我想要一些更有活力的东西。我想从数据库提供的 observableArray 开始。这个 observableArray 看起来像这样:

var vehicles = ko.observableArray([
    {
     Id: 1,
     Brand: "Volkswagen",
     Type: "Golf"
    },
    {
     Id: 2,
     Brand: "Volkswagen",
     Type: "Sharan" 
    },
    {
     Id: 3,
     Brand: "BMW",
     Type: "118i"
    }
    {
     Id: 4,
     Brand: "BMW",
     Type: "525D"
    }
 ]);

我的问题:是否有可能有一个基于这个单一 observableArray 的解决方案来构造选择。也许借助计算属性来检索 optgroup/options?

谢谢。

【问题讨论】:

  • 哇——我从来没有意识到这是一个内置功能。当我看到这种风格时,我总是认为它是一种自定义(尽管有点丑)下拉菜单。现在我想为了它而使用它:-)

标签: knockout.js


【解决方案1】:

这是执行此操作的方法之一。它不是最佳的,但效果很好:

var ViewModel = function () {
    var self = this;
    self.vehicles = ko.observableArray([{
        Id: 1,
        Brand: "Volkswagen",
        Type: "Golf"
    }, {
        Id: 2,
        Brand: "Volkswagen",
        Type: "Sharan"
    }, {
        Id: 3,
        Brand: "BMW",
        Type: "118i"
    }, {
        Id: 2,
        Brand: "BMW",
        Type: "525D"
    }]);

    self.brands = ko.computed(function(){
        var list = ko.utils.arrayMap(self.vehicles(), function(item){
            return item.Brand;
        });

        return ko.utils.arrayGetDistinctValues(list);
    });
};

ko.applyBindings(new ViewModel());

<select data-bind="foreach: brands">
    <optgroup data-bind="attr: {label: $data}, foreach: $parent.vehicles">
    <!-- ko if: Brand == $parent -->
        <option data-bind="text: Type"></option>
    <!-- /ko -->
    </optgroup>
</select>

小提琴:http://jsfiddle.net/HPhmB/55/

【讨论】:

  • 非常感谢。你帮了我很多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 2013-12-02
  • 2013-02-28
  • 1970-01-01
相关资源
最近更新 更多