问题是当选择选项被更改时,值没有被更新。
因此,当我将本田改为丰田时,第二选择的选项变得很好,但是选择模型可以观察不到。我一定错过了什么。
JavaScript的:
function ViewModel() {
var self = this;
self.selectedMake = ko.observable()
self.selectedModel = ko.observable()
self.makes = ["Honda", "Toyota"];
self.models = ko.computed(function () {
if (self.selectedMake() === "Honda") return ["CRV", "Accord"];
if (self.selectedMake() === "Toyota") return ["Rav4", "Camry"];
return [];
});
}
$(function () {
ko.applyBindings(new ViewModel());
});
HTML:
<select data-bind="value: selectedMake, options: makes"></select>
<select data-bind="value: selectedModel, options: models"></select>
<p>Selected make: <b data-bind="text:selectedMake"></b></p>
<p>Selected model: <b data-bind="text:selectedModel"></b></p>
答案 0 :(得分:10)
在GitHub上找到答案。如果有人会发现这个问题,请将其重新寄到此处。
这是绑定顺序重要的情况。见http://knockoutjs.com/documentation/binding-syntax.html#notes_for_multiple_bindings_on_a_single_element
<select data-bind="options: makes, value: selectedMake"></select>
<select data-bind="options: models, value: selectedModel"></select>
jsFiddle:http://jsfiddle.net/n4VyD/4/
答案 1 :(得分:2)
我不确定为什么它不能正常工作,但如果您设置了模型订阅,则可以手动更改所选模型。
function ViewModel() {
var self = this;
self.selectedMake = ko.observable()
self.selectedModel = ko.observable()
self.makes = ["Honda", "Toyota"];
self.models = ko.computed(function () {
if (self.selectedMake() === "Honda") return ["CRV", "Accord"];
if (self.selectedMake() === "Toyota") return ["Rav4", "Camry"];
return [];
});
self.models.subscribe(function(value) {
self.selectedModel(value[0]);
});
}
$(function () {
ko.applyBindings(new ViewModel());
});