我有一个使用Knockout的CRUD单页,一切正常,我从JSON调用获取数据,它用对象列表填充自动化的可观察数组。 我可以在该数组中添加或编辑单个项目。
问题在于格式化我在表格中显示的货币(数字)列以及对象列表。我在很多方面尝试过使用js函数,但是当我更新项目时,表格的格式化货币量不会更新。 如果我使用绑定来格式化字段,那么我无法编辑它,因为它会转换为字符串。
我需要的是我的货币列的单向绑定(自动更新)格式化列。但是我无法立即创建计算列,因为我正在使用自动化对象数组。我尝试使用http://knockoutjs.com/documentation/plugins-mapping.html中的示例添加计算机,但我不知道如何将它与映射数组一起使用。
我的viewmodel是这样的:
//--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
}
谢谢!
答案 0 :(得分:0)
当您将文本设置为函数的返回值(text: formatCurrency(Balance)
)时,它只运行一次。它不是一个可观察的,所以它的价值永远不会再次更新。你需要的是一个真正的蓝色计算可观察量。为了实现这一点,您必须自定义映射。因此,只需为您的个人帐户对象创建一个视图模型,然后将返回的数据映射到该模型。
var SingleAccountViewModel = function (account) {
var model = ko.mapping.fromJS(account);
model.FormattedBalance = ko.computed(function () {
return formattedCurrency(model.Balance);
});
return model;
}
然后,当您从AJAX响应中获取数据时:
$.postJSON(appURL + 'Accounts/GetList', function (data) {
self.accounts($.map(data.Records, SingleAccountViewModel));
});
jQuery.map方法将遍历数组并返回一个由传递函数的返回值组成的新数组。在这种情况下,这是您的视图模型,现在将对其进行计算FormattedBalance
,您可以绑定它。