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/
The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.
$root. This is the main view model object in the root context, i.e., the topmost parent context. It's usually the object that was passed to ko. applyBindings . It is equivalent to $parents[$parents.
Activating Knockout But since the browser doesn't know what it means, you need to activate Knockout to make it take effect. To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel);
KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.
Got an answer on GitHub. Reposting it here if someone will find this question.
This is a case where the order of the bindings matter. 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/
I'm not sure why it's not working as is, but if you set up a subscription to models, you can manually change the selected model.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With