我想根据汽车品牌加载第二个选择。我将selectedIndexes绑定到ko.observable()变量。我知道我可以通过使用optionsValue:'id'并将值绑定到observable来实现这一点,但我需要在我的项目中使用selectedIndex。谢谢
jsfiddle http://jsfiddle.net/diegopitt/xg8q5esu/
我的viewModel:
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>
答案 0 :(得分: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;
});