我正在开发一个HTML电子表格,使用Knockout.js进行数据绑定。我决定采用一种直截了当的,虽然没有优雅的解决方案,这样可以让我更好地查看和控制每个绑定上发生的事情,但即便如此,我遇到了包含两个项目的障碍:百分比和放置逗号在计算结果中。
这是JSFiddle:http://jsfiddle.net/WebMagi/NqBRT/
我设法在Total上使用:.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
,但是当我将它添加到两个项目(viewModel.C11和viewModel.D11)时,它打破了表格。
至于百分比,我正在尝试执行以下操作:(C11-D11)/ C11,这对于显示折扣很有用。
有想法如何解决这两个问题的任何人?
这是Knockout代码:
var viewModel = {
C1: ko.observable(24.37),
C2: ko.observable(1.5),
C3: ko.observable(""),
C4: ko.observable("4"),
C5: ko.observable("4"),
C6: ko.observable("8"),
C8: ko.observable(""),
C9: ko.observable(""),
C10: ko.observable(""),
C11: ko.observable(""),
C12: ko.observable(""),
D1: ko.observable(38.62),
D2: ko.observable(1.5),
D3: ko.observable(""),
D4: ko.observable("9"),
D5: ko.observable("4"),
D6: ko.observable("8"),
D8: ko.observable(""),
D9: ko.observable(""),
D10: ko.observable(""),
D11: ko.observable(""),
D12: ko.observable(""),
D13: ko.observable("")
};
viewModel.C3 = ko.computed(function () {
return (this.C1() * this.C2()).toFixed(2);
}, viewModel);
viewModel.D3 = ko.computed(function () {
return (this.D1() * this.D2()).toFixed(2);
}, viewModel);
viewModel.C8 = ko.computed(function () {
return (this.C3() / this.C4()).toFixed(2);
}, viewModel);
viewModel.D8 = ko.computed(function () {
return (this.D3() / this.D4()).toFixed(2);
}, viewModel);
viewModel.C9 = ko.computed(function () {
return (this.C8() * this.C5()).toFixed(2);
}, viewModel);
viewModel.D9 = ko.computed(function () {
return (this.D8() * this.D5()).toFixed(2);
}, viewModel);
viewModel.C10 = ko.computed(function () {
return (this.C9() * this.C6()).toFixed(2);
}, viewModel);
viewModel.D10 = ko.computed(function () {
return (this.D9() * this.D6()).toFixed(2);
}, viewModel);
viewModel.C11 = ko.computed(function () {
return (this.C10() * 365).toFixed(2);
}, viewModel);
viewModel.D11 = ko.computed(function () {
return (this.D10() * 365).toFixed(2);
}, viewModel);
//viewModel.C12 = ko.computed(function () {
// return (this.C11() - this.D11()) / this.C11().toFixed(2);
//}, viewModel);
viewModel.D13 = ko.computed(function () {
return (this.C11() - this.D11()).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}, viewModel);
ko.applyBindings(viewModel);
感谢。
答案 0 :(得分:1)
(this.C11() - this.D11()) / this.C11().toFixed(2);
的问题在于您在字符串上调用toFixed
。在另一组括号中围绕整个计算将解决问题。
((this.C11() - this.D11()) / this.C11()).toFixed(2);
通过格式化C11
和D11
来中断应用程序的原因是其他计算的observable正在尝试在其计算中使用格式化的返回值。由于D13
没有其它依赖于它的可观察对象,因此它可以工作。
您需要提供一种区分计算值和渲染/格式化值的方法。快速简便的方法是在模型上提供实用程序功能以执行格式化。
viewModel.format = function(obs){
return obs().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Html:<span data-bind="text: format(C11)"></span>