拥有一组可观察的银行交易,其中包含金额等。
我试图保持一个可计算的运行平衡,但我似乎陷入了无限循环和各种不良情况。
这是我能想到的最简单的小提琴 - http://jsfiddle.net/Nnyxx/2/
JS:
var transactions = [{Amount: -100}, {Amount: 125}, {Amount: 10}, {Amount: 25}, {Amount: -125}, {Amount: 400}];
var ViewModel = function() {
this.OpeningBalance = ko.observable(1000);
this.RunningBalance = ko.observable(this.OpeningBalance());
this.ClosingBalance = ko.observable(this.RunningBalance());
this.UpdateRunningBalance = ko.computed({
read: function() {
return this.RunningBalance();
},
write: function(amount) {
this.RunningBalance(this.RunningBalance() + amount);
return amount;
}
}, this);
this.Transactions = ko.observableArray(ko.mapping.fromJS(transactions)());
}
var model = new ViewModel();
ko.applyBindings(model);
HTML:
<table>
<thead>
<tr>
<th width="150"></th>
<th width="150">Money Out</th>
<th width="150">Money In</th>
<th>Balance</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="3"><strong>Opening Balance</strong></td>
<th>
<span data-bind="text: OpeningBalance"></span>
</th>
</tr>
<!-- ko foreach: Transactions -->
<tr>
<td></td>
<!-- ko if: Amount() < 0 -->
<td data-bind="text: Amount"></td>
<td></td>
<!-- /ko -->
<!-- ko if: Amount() > 0 -->
<td></td>
<td data-bind="text: Amount"></td>
<!-- /ko -->
<td>
<span data-bind="text: $root.UpdateRunningBalance(Amount())"></span>
</td>
</tr>
<!-- /ko -->
<tr>
<td colspan="3"><strong>Closing Balance</strong></td>
<th>
<span data-bind="text: ClosingBalance"></span>
</th>
</tr>
</tbody>
</table>
它仍然不完整,因为我最终围绕如何让期初余额显示和重新计算。
流动余额需要是可观察的,因此如果期初余额或交易发生变化,它将重新计算。
期末余额也需要是最终的流动余额。