6

Problem is when select options got changed value is not being updated.

So when I change Honda to Toyota, options in second select got changed fine, but selectedModel observable not. I must have missed something.

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>

JS Fiddle: http://jsfiddle.net/apuchkov/n4VyD/

4

2 回答 2

11

在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/

于 2013-04-26T13:49:43.900 回答
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());
});

小提琴

于 2013-04-19T15:54:27.590 回答