使用 select selectedIndex 按 id 匹配项目的 Knockout 过滤项目

Knockout filtering items using select selectedIndex matching items by id

我想根据汽车品牌加载第二个 select。我将 selectedIndexes 绑定到 ko.observable() 变量。我知道我可以通过使用 optionsValue : 'id' 并将值绑定到可观察对象来实现这一点,但我需要在我的项目中使用 selectedIndex 。谢谢

jsfiddle http://jsfiddle.net/diegopitt/xg8q5esu/

我的视图模型:

ko.bindingHandlers.selectedIndex = {
    init: function(element, valueAccessor) {
        ko.utils.registerEventHandler(element, "change", function() {
             var value = valueAccessor();
            if (ko.isWriteableObservable(value)) {
               value(element.selectedIndex);   
            }
        });
    }
};

var viewModel = function(){
    var self = this;
    self.selectedMake = ko.observable();
    self.selectedType = ko.observable();

    self.makes = [
            {id:1, name: 'Dodge'},
            {id:2, name: 'BMW'}
    ];
    self.types = [
            {id: 1, make:1, name:'neon'},
            {id: 2, make:2, name:'328i'}
    ];
    self.carTypes = ko.computed(function(){
        return ko.utils.arrayFilter(self.types, function(item){
            return item.make === self.selectedMake();
        });
    });
    self.matchingTypes = ko.computed(function () {
        return ko.utils.arrayFilter(self.carTypes(), function (item, index) {
            return item.id === self.selectedType();
        });
    }); 
};
var model = new viewModel();
ko.applyBindings(model);

HTML:

<select id="make" class="form-control select pull-left" data-bind="options: makes, selectedIndex: selectedMake, optionsText : 'name'"></select>
<select id="type" class="form-control select pull-left" data-bind="options: carTypes, selectedIndex: selectedType, optionsText : 'name'"></select>

由于 selectedMake 设置为索引,self.carTypes 计算需要比较索引而不是值:

self.carTypes = ko.computed(function(){
    var carTypes = [];

    if (self.selectedMake() < self.types.length) {
        carTypes.push(self.types[self.selectedMake()])
    }

    return carTypes;
});

JsFiddle