Knockoutjs does not update value when changing selected parameters

The problem is that the selected parameters received by the changed value are not updated.

So, when I change Honda to Toyota, the options in the second selection change fine, but the selectedModel is not observed. 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/

+5
source share
2 answers

Got a response on GitHub . Posting it here if someone finds this question.

This is the case when the order of the bindings matters. See 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/

+10

, , , , .

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());
});

Fiddle

+2

All Articles