KO Dependent Observable Example
KO Dependent Observable Example
HTML
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.0.js"></script>
<select data-bind="options:countries, optionsText : 'cname', value:selectedCountry, optionsCaption:'Select...'"></select>
<select data-bind="options:selectedStates, optionsText : 'sname', value:selectedState, optionsCaption:'Select...'"></select> <br/><br/>
<span data-bind="text:selectedStateName"></span><span data-bind="text:selectedCountryName"></span>
JavaScript
$(document).ready(function() {
var viewModel = function() {
var country = function() {
this.key = ko.observable();
this.cname = ko.observable();
};
var state = function() {
this.countryKey = ko.observable();
this.sname = ko.observable();
};
var countries = ko.observableArray([]);
var states = ko.observableArray([]);
var load = function() {
// add countries
countries.push(new country().key(USA).cname("USA"));
countries.push(new country().key(2).cname("India"));
// add states
states.push(new state().countryKey(USA).sname("New Jersey"));
states.push(new state().countryKey(USA).sname("New York"));
states.push(new state().countryKey(USA).sname("Ohio"));
states.push(new state().countryKey(USA).sname("Kentucky"));
states.push(new state().countryKey(2).sname("MP"));
states.push(new state().countryKey(2).sname("UP"));
states.push(new state().countryKey(2).sname("Maharashtra"));
};
// keep track of selected country
var selectedCountry = ko.observable("");
var selectedState = ko.observable("");
var selectedCountryName = ko.computed(function() {
var cntry = selectedCountry();
if (cntry) {
return cntry.cname();
}
return "";
});
var selectedStateName = ko.computed(function() {
var st = selectedState();
if (st) {
return st.sname() + " , ";
}
return "";
});
// change state selection based on country selection
var selectedStates = ko.dependentObservable(function() {
var cntry = selectedCountry();
var cntryKey;
if (cntry) {
cntryKey = cntry.key();
return...