有一個可觀察的銀行交易數組,其中包含金額等。敲除js計算出的運行餘額無限循環
我試圖保持運行平衡作爲可計算但我似乎陷入無限循環和各種惡劣。
這是我能想出的最簡單的小提琴 - 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>
它仍然是不完整的,因爲我最終繞來繞去在如何獲得期初餘額顯示和recal的圈子裏culate。
運行餘額需要是可觀察的,所以如果期初餘額或交易發生變化,它將重新計算。
此外期末餘額需要是最終運行餘額。
真棒,謝謝你的幫助。正式注意到關於語法和舍入的評論。 – Colin
很高興幫助。您可以查看[extenders](http://knockoutjs.com/documentation/extenders.html)來管理貨幣價值,這些貨幣價值恰當地自動調整。 – Tomalak