我正在尝试找出当用户选择特定州时如何更新我的税率。这是我的代码(剥离了不相关的数据):
<select data-bind="event: {change: checkTax }">
<option value="PA">PA</option>
<option value="FL">FL</option>
</select>
<span data-bind="text: taxedItems"></span>
var MainViewModel = function() {
var self = this;
var response = arrayFromJson;
// ...
self.checkTax = function (viewModel, event) {
if (event.target.value === "FL") {
userTax = "this should appear";
}
};
self.taxedItems = ko.pureComputed(function() {
taxcost = userTax;
return taxcost;
});
self.CartItems($.map(response, function(item) {
return new AppViewModel(item);
}));
};
function AppViewModel(data) {
var self = this;
// ...
}
ko.applyBindings(new MainViewModel());
首先,
taxedItems
应该为空,然后在用户将其更改为FL
之后,taxedItems
应该说出"this should appear"
,但这不是完全跳过更新taxedItems
的全部。有人知道为什么是这样吗? 最佳答案
如果要在mainViewModel中包含taxedItems,可以执行以下操作:
虚拟机
var MainViewModel = function () {
var self = this;
self.CartItems = ko.observableArray([]);
self.States = ko.observableArray([{Value:"CA",Name:"CA"},
{Value:"FL",Name:"FL"},
{Value:"NY",Name:"NY"},
{Value:"VG",Name:"VG"},
{Value:"TX",Name:"TX"}
]);
var response = [{ }];
self.CartItems($.map(response, function (item) {
return new AppViewModel(item);
}));
self.TaxedItems = ko.observable();
self.SelectedState = ko.observable(0);
self.SelectedState.subscribe(function (StateValue) {
if(StateValue ==='FL'){
self.TaxedItems('this should appear');
}else{
self.TaxedItems('');
}
})
}
function AppViewModel(data) {
var self = this;
// ...
}
ko.applyBindings(new MainViewModel());
查看:
<select data-bind="foreach: States ,value:SelectedState">
<option data-bind="visible:$index()==0" value="0" disabled>Select Tax State..</option>
<option data-bind="value: Value,text:Name"></option>
</select>
<br>
<span data-bind="text: TaxedItems"></span>
示例:http://jsfiddle.net/GSvnh/5095/