如果选择发生变化,则不会通知绑定。当选择改变时,如果所选国家的'eu'设置为“1”,我想要发生一些事情。
<select data-bind="options: countries,
optionsText: function(item) {
return item.country_name
},
value:selectedCountry">
</select>
<!-- These *ARE* all updated when country selection changes -->
<div data-bind="visible: selectedCountry()">
<span data-bind="text: selectedCountry().eu"></span>
<span data-bind="text: selectedCountry().country_name"></span>
<span data-bind="text: selectedCountry().country_code"></span>
</div>
<!-- This is *NOT* updated -->
<!-- ko if: selectedCountry().eu === "1" -->
<span>You selected country from EU
</span>
<!-- /ko -->
'国家'(样本)如下。
{
"countries": [
{
"country_code": "BD",
"country_name": "Bangladesh",
"eu": "0"
},
{
"country_code": "BE",
"country_name": "Belgium",
"eu": "1"
}
]
}
更新
我正在使用CoffeeScript
@selectedCountry = ko.observable()
@countries = ko.observableArray []
答案 0 :(得分:1)
这对我这个小提琴很有用。不知道我的代码和你的代码之间有什么区别,因为我们看不到你的JavaScript。
https://jsfiddle.net/xggu9Lv2/7/
var countries = [
{
"country_code": "A2",
"country_name": "Satellite Provider",
"eu": "0"
},
{
"country_code": "A2",
"country_name": "Satellite Provider",
"eu": "1"
}
]
var ViewModel = function() {
var self = this;
self.countries = ko.observableArray(countries);
self.selectedCountry = ko.observable(null);
};
ko.applyBindings(new ViewModel());
<select data-bind="options: countries,
optionsText: function(item) {
return item.country_name
},
value:selectedCountry">
</select>
<div data-bind="visible: selectedCountry()">
<span data-bind="text: selectedCountry().eu"></span>
<span data-bind="text: selectedCountry().country_name"></span>
<span data-bind="text: selectedCountry().country_code"></span>
</div>
<!-- ko if: selectedCountry().eu === "1" -->
<span>You selected country from EU
</span>
<!-- /ko -->