我想根据汽车品牌加载第二个选择。我将 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>