gpt4 book ai didi

javascript - 下拉更改加载时 knockout 火订阅

转载 作者:行者123 更新时间:2023-12-03 09:32:02 25 4
gpt4 key购买 nike

我必须在 ko 中使用 valueHasMutated 方法来在页面加载时触发订阅,同时绑定(bind)国家/地区列表下拉列表,以便我可以根据所选下拉列表获取状态,是否有替代方法?在不使用此方法的情况下如何触发国家/地区订阅?

Country List: <select id="CountryDropdownList" data-bind="options: viewModel.CountryCollection,optionsText:'CountryName',optionsValue:'CountryName',value:viewModel.SelectedCountry"></select>
State List: <select id="StateDropdownList" data-bind="options: viewModel.StateCollection,optionsText:'StateName',optionsValue:'StateName',value:viewModel.SelectedState"></select>

<script>
var viewModel = ko.mapping.fromJS(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
console.log(viewModel.SelectedState()); //State3 the initial value

viewModel.SelectedCountry.subscribe(function (newSelectedCountry) {
alert(newSelectedCountry);
console.log(viewModel.SelectedState()); //undefined why?
$.ajax({
url: 'Home/GetStateList?Country=' + newSelectedCountry,
success: function (data) {
viewModel.StateCollection(ko.mapping.fromJS(data)());
console.log(viewModel.SelectedState()); //state0 why?

}
})
});


ko.applyBindings(viewModel);
$(function () {
//to fire subscription
viewModel.SelectedCountry.valueHasMutated();
})

</script>

最佳答案

不要在 HTML 中的绑定(bind)变量上指定 viewmodel.。当您调用 ko.applyBindings 时,它会为您的绑定(bind)变量创建默认上下文。

如果 value 绑定(bind)变量的值与任何选项值都不匹配,它将(默认情况下)设置为未定义。这可能就是正在发生的事情(请参阅您的“未定义原因?”评论)。尝试添加valueAllowUnset选项。我可能解释错了。但无论如何,您都需要根据选项检查初始值。

关于javascript - 下拉更改加载时 knockout 火订阅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31473994/

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