gpt4 book ai didi

knockout.js - knockout 手动订阅不会在下拉列表更改时触发

转载 作者:行者123 更新时间:2023-12-04 18:46:42 26 4
gpt4 key购买 nike

另一个我似乎无法找到帮助的 knockout 问题。

我基本上是在尝试实现级联下拉列表。前几天我请求帮助了解如何解析我的复杂 JSON(它来自 cakePHP Controller 。前几天我收到的帮助非常好,但我遇到了另一个小问题。

我遇到的问题是,在调用 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/

再次对这个问题的任何帮助将不胜感激,一旦我掌握了 knockout 的窍门,它就会容易得多。

谢谢

最佳答案

一些问题:

  • 你忘了做 .bind(this)第一次订阅
  • this.viewModel而不仅仅是 this
  • 你有 optionsValue: "Id"而不是 optionsValue: "id"
  • 你有 optionsText: "County"而不是 optionsText: "county"
  • 您的 countyData的数组被称为 country而不是 counties

  • 更新 fiddle : http://jsfiddle.net/antishok/jbrr5/23/

    关于knockout.js - knockout 手动订阅不会在下拉列表更改时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13089368/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com