我似乎无法找到帮助的另一个淘汰赛问题。
我基本上试图实现级联下拉列表。前几天我请求帮助解析我的复杂JSON(来自cakePHP控制器。我前几天收到的帮助非常好,但我遇到了另一个小问题。
我遇到的问题是我在调用JSON以获取国家/地区列表后更新了viewModel。一旦我填充下拉列表,我想要显示县列表,最终显示城市列表,但我还没有。不幸的是,当我改变时,我从列表中选择一个国家,我的观察不会触发。我怀疑是因为我创建了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/
再次对这个问题的任何帮助都会受到赞赏,一旦我获得了淘汰赛,它就会变得更加容易。
谢谢
答案 0 :(得分:6)
一些问题:
.bind(this)
this.viewModel
而非this
optionsValue: "Id"
而不是optionsValue: "id"
optionsText: "County"
而不是optionsText: "county"
countyData
数组名为country
而不是counties