是否可以使用knockout js对此场景进行建模?
说我有3个字段:
Current Income
:如果我更改此值,则Retirement Income
需要更新为(Current Income * Percentage of Current Income) / 100
Retirement Income
:如果我更改此值,则Percentage of Current Income
需要更新为(Retirement Income/Current Income) * 100
Percentage of Current Income
:如果我更改此值,则Retirement Income
需要更新为(Current Income * Percentage Of Current Income) / 100
这是某种循环依赖吗?可以使用knockout js建模吗?我假设所有字段都需要计算...但我不确定如何设置默认值或使用尚未声明的计算的observable。
jsfiddle起点:http://jsfiddle.net/LkqTU/4482/
答案 0 :(得分:2)
您可以使用read/write computed
:
var ViewModel = function() {
var self = this;
self.currentIncome = ko.observable(1000);
self.currentIncomePercent = ko.observable(5);
self.retirementIncome = ko.computed({
read: function() {
var result = self.currentIncome() * self.currentIncomePercent() / 100;
return result.toFixed(2);
},
write: function(value) {
var result = value / self.currentIncome() * 100;
self.currentIncomePercent(result.toFixed(2));
}
});
};
ko.applyBindings(new ViewModel());