0

我想根据汽车品牌加载第二个选择。我将 selectedIndexes 绑定到 ko.observable() 变量。我知道我可以通过使用 optionsValue : 'id' 并将值绑定到 observable 来实现这一点,但我需要在我的项目中使用 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>
4

1 回答 1

0

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

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

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

    return carTypes;
});

提琴手

于 2015-07-08T05:50:21.413 回答