【发布时间】:2013-03-23 21:27:17
【问题描述】:
我有一个使用 Knockout 的 CRUD 单页,一切正常,我从 JSON 调用中获取数据,它用对象列表填充了一个自动映射的可观察数组。 我可以在该数组中添加或编辑单个项目。
问题在于格式化我在表格中显示的带有对象列表的货币(数字)列。我尝试过在很多方面使用 js 函数,但是当我更新项目时,表格的格式化货币金额不会更新。 如果我使用绑定来格式化字段,则无法编辑它,因为它会转换为字符串。
我需要一个用于货币列的单向绑定(自动更新)格式列。但我无法立即创建计算列,因为我使用的是自动映射的对象数组。我尝试使用http://knockoutjs.com/documentation/plugins-mapping.html 中的示例添加计算,但我不知道如何将它与映射数组一起使用。
我的视图模型是这样的:
//--Accounts - Viewmodel Knockout
function accountViewModel() {
var self = this;
self.accounts = ko.observableArray(); //this is the list of objects
self.account = ko.observable(); //single item for creating or editing
//--get list------
self.getAccounts = function () {
$.postJSON(appURL + 'Accounts/GetList', function (data) {
ko.mapping.fromJS(data.Records, {}, self.accounts);
});
};
self.getAccounts();
}
每个帐户项目都有如下字段: -ID -姓名 -Balance
在页面中使用:
<table data-bind="visible: accounts().length > 0">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Name</th>
<th scope="col">Balance</th>
</tr>
</thead>
<tbody id="accounts" data-bind="foreach: accounts">
<tr>
<td><span data-bind="text: Id"></span></td>
<td><a href="" data-bind="text: Name, click: $root.getdetails" style="display:block;"></a></td>
<td style="text-align:right;">
<span data-bind="text: formatCurrency(Balance), css: { negative: Balance() < 0, positive: Balance() > 0 }"></span>
</td>
</tr>
</tbody>
</table>
formatCurrency 只是一个用于格式化数字的js函数:
formatCurrency = function (value) {
debugger;
if (value!=undefined)
return "$" + withCommas(value().toFixed(2));
//had to use value() instead of value, because of toFixed
}
谢谢!
【问题讨论】:
-
关于如何使用映射插件并在映射对象上计算的可能重复:stackoverflow.com/questions/15480316/…
标签: asp.net-mvc knockout.js crud knockout-mapping-plugin