チェーン dropDownLists の簡単な実装を次に示します。
var registryEpisode = function() {
var self = this;
self.registry = ko.observable(new registry());
self.episodeType = ko.observable(new episodeType());
};
var episodeType = function(id, name) {
var self = this;
self.id = ko.observable(id), self.name = ko.observable(name);
};
var registry = function() {
var self = this;
self.id = ko.observable(""), self.name = ko.observable("");
};
var vm = function() {
var self = this;
self.selectedRegistry = ko.observable("");
self.registryEpisodeTypes = ko.observableArray([]);
self.addRegistryEpisodeType = function(episodeType, registry) {
var regEpisode = new registryEpisode();
regEpisode.registry = registry;
regEpisode.episodeType = episodeType;
self.registryEpisodeTypes.push(regEpisode);
}.bind(this);
self.getRegistries = function() {
var hashCheck = {};
var result = ko.observableArray([]);
ko.utils.arrayMap(self.registryEpisodeTypes(), function(item) {
if (hashCheck["" + item.registry.id()] === null || hashCheck["" + item.registry.id()] === undefined) {
hashCheck["" + item.registry.id()] = item.registry.name();
result.push({
"name": item.registry.name(),
"value": item.registry.id()
});
}
});
return result;
}
self.getEpisodes = ko.dependentObservable(function() {
var ret = self.registryEpisodeTypes();
var selectedRegistryItem = self.selectedRegistry();
if (selectedRegistryItem === null || selectedRegistryItem === undefined || selectedRegistryItem === "")
return ;
var result = ko.observableArray([]);
ko.utils.arrayMap(ret, function(item) {
if (item.registry.id() == selectedRegistryItem) result.push({
"name": item.episodeType.name(),
"value": item.episodeType.id()
});
});
console.log(ko.toJSON(result));
return result;
});
}
var viewModel = new vm();
var breakingBad = new registry();
breakingBad.id("1000");
breakingBad.name("Breaking Bad");
viewModel.addRegistryEpisodeType(new episodeType("1", "E1-breakingBad"), breakingBad);
viewModel.addRegistryEpisodeType(new episodeType("2", "E2-breakingBad"), breakingBad);
viewModel.addRegistryEpisodeType(new episodeType("3", "E3-breakingBad"), breakingBad);
var trueBlood = new registry();
trueBlood.id("1001");
trueBlood.name("True Blood");
viewModel.addRegistryEpisodeType(new episodeType("1", "E1-trueBlood"), trueBlood);
viewModel.addRegistryEpisodeType(new episodeType("2", "E2-trueBlood"), trueBlood);
viewModel.addRegistryEpisodeType(new episodeType("3", "E3-trueBlood"), trueBlood);
ko.applyBindings(viewModel);
<div>
<span data-bind="text:selectedRegistry"></span>
</div>
<div>
<select data-bind="options:getRegistries(),optionsText:'name',optionsValue:'value',value:selectedRegistry"></select>
</div>
<div>
<select data-bind="options:getEpisodes(),optionsText:'name',optionsValue:'value'"></select>
</div>
getEpisodes というdependentObservable を作成します。selectedRegistry がこの episodeList を変更するたびに、再計算されます。