question about references between objects
http://www.knockmeout.net/2011/04/utility-functions-in-knockoutjs.html
by Doug Hill
HTML
<script src="https://github.com/downloads/SteveSanderson/knockout/knockout-2.0.0.debug.js"></script>
<table>
<tr>
<td>Country</td>
<td>
<select
data-bind="options: countries, optionsText: 'countryName', value: selectedCountry, optionsCaption: 'Choose...'">
</select>
</td>
</tr>
<tr data-bind="visible: selectedCountry">
<td>State</td>
<td>
<select
data-bind="options: selectedStates, optionsText: 'stateName', optionsValue: $data, value: selectedState, optionsCaption: 'Choose...'">
</select>
</td>
</tr>
<tr data-bind="visible: selectedState">
<td>City</td>
<td>
<select
data-bind="options: selectedCities, optionsText: 'cityName', optionsValue: 'cityName', value: selectedCity, optionsCaption: 'Choose...'">
</select>
</td>
</tr>
</table>
JavaScript
var country = function (countryId, countryName) {
this.countryId = ko.observable(countryId);
this.countryName = ko.observable(countryName);
};
var state = function (stateId, stateName, countryId) {
this.stateId = ko.observable(stateId);
this.stateName = ko.observable(stateName);
this.countryId = ko.observable(countryId);
};
var city = function (cityId, cityName, stateId) {
this.cityId = ko.observable(cityId);
this.cityName = ko.observable(cityName);
this.stateId = ko.observable(stateId);
}
var viewModel = {
countries: ko.observableArray([
new country(1, "USA"),
new country(2, "Germany"),
new country(3, "India")
]),
selectedCountry: ko.observable(), // Nothing selected by default
states: ko.observableArray([
new state(101, "California", 1),
new state(201, "Berlin", 2),
new state(301, "Kerala", 3)
]),
selectedState: ko.observable(),// Nothing selected by default
cities: ko.observableArray([
new city(101, "Los Angeles", 101),
new city(201, "Kraka", 201),
new city(301, "Sierra", 301)
]),
selectedCity: ko.observable()// Nothing selected by default
};
viewModel.selectedStates = ko.dependentObservable(function () {
var country = this.selectedCountry(), countryId;
if (country) {
countryId = country.countryId();
return ko.utils.arrayFilter(this.states(), function(state) {
return state.countryId() === countryId;
});
}
return [];
}, viewModel);
viewModel.selectedCities = ko.dependentObservable(function () {
var state = this.selectedState(), stateId;
if (state) {
stateId = state.stateId();
return ko.utils.arrayFilter(this.cities(), function(city) {
return city.stateId() === stateId;
});
}
return [];
},...