另一个我似乎无法找到帮助的淘汰赛问题。
我基本上是在尝试实现级联下拉菜单。前几天我就如何解析我的复杂 JSON(来自 cakePHP 控制器)请求帮助。前几天我收到的帮助非常好,但我遇到了另一个小问题。
我遇到的问题是在调用 JSON 以获取国家/地区列表后,我正在更新 viewModel。填充下拉列表后,我希望显示县列表并最终显示城市列表,但我还没有。不幸的是,当我更改时,我从列表中选择了一个国家,我的 observable 不会触发。我怀疑这是因为我已经this.selectedCountry = ko.observable()
使用映射创建和更新了,但我不知道这应该是什么有效选项。当然,我也可以成为标志:/
我有以下代码
HTML:
<select id="countries"
data-bind='
options: countries,
optionsValue : "Id",
optionsText: "country",
optionsCaption: "[Please select a country]",
value: selectedCountry'>
</select>
<select id="counties"
data-bind='
options: selectedCountry() ? counties : null,
optionsValue : "Id",
optionsText: "County",
optionsCaption: "[Please select a county]",
value: selectedCounty,
visible: (counties() && counties().length > 0)'>
</select>
Javascript
var countryData= {"countries":[{"Country":{"id":"1","country":"England"}},{"Country":{"id":"2","country":"Wales\/Cymru"}},{"Country":{"id":"3","country":"Scotland"}},{"Country":{"id":"4","country":"Republic of Ireland"}},{"Country":{"id":"5","country":"Northern Ireland"}}]};
var countyData= {"country":[{"County":{"id":"1","county":"Essex"}}]};
var countryMappingOptions = {
'countries': {
'update': function (options) {
return ko.mapping.fromJS(options.data.Country);
},
'ignore': ["selectedCountry"]
}
};
var countyMappingOptions = {
'counties': {
'update': function (options) {
return ko.mapping.fromJS(options.data.County);
}
}
};
var vm= function () {
this.selectedCountry = ko.observable();
this.selectedCounty = ko.observable();
this.countries = ko.mapping.fromJS([]);
this.counties = ko.mapping.fromJS([]);
// Whenever the continent changes, reset the country selection
this.selectedCountry.subscribe(function (countryId) {
alert(countryId);
this.selectedCounty(undefined);
this.counties(undefined);
if (countryId != null) {
ko.mapping.fromJS(countyData, countyMappingOptions,this.viewModel );
}
});
this.selectedCounty.subscribe(function (countryId) {
alert(countryId);
} .bind(this));
};
var viewModel = new vm();
ko.applyBindings(viewModel );
console.log(viewModel .countries());
ko.mapping.fromJS(countryData, countryMappingOptions ,viewModel );
console.log(viewModel .selectedCountry() );
我还创建了一个 JSFiddle 来演示这里的问题http://jsfiddle.net/jbrr5/21/
再次感谢您对这个问题的任何帮助,一旦我掌握了淘汰赛的窍门,它就会变得容易得多。
谢谢</p>