【发布时间】:2013-05-14 13:11:08
【问题描述】:
使用 KnockOut - 在添加到 MVC .Net 代码之前,我正在尝试构建主细节/项目应用程序的基础知识。
我想要做的只是有一个简单的项目、价格、税金 - 以及一个计算列来显示每个项目的含税金额:
客户端 KnockOut 视图模型是:
var GiftModel = function(gifts) {
var self = this;
self.gifts = ko.observableArray(gifts);
self.formattedPrice = ko.computed(function() {
var pricet = self.gifts().price;
return pricet ? "$" + pricet.toFixed(2) * (1 + self.gifts().tax : "None";
});
self.addGift = function() {
self.gifts.push({
name: "",
price: "",
tax:0
});
};
self.removeGift = function(gift) {
self.gifts.remove(gift);
};
self.save = function(form) {
alert("Could now transmit to server: " + ko.utils.stringifyJson(self.gifts));
// To actually transmit to server as a regular form post, write this: ko.utils.postJson($("form")[0], self.gifts);
};
};
var viewModel = new GiftModel([
{ name: "Tall Hat", price: "39.95", tax:17.5},
{ name: "Long Cloak", price: "120.00", tax:20}
]);
ko.applyBindings(viewModel);
// Activate jQuery Validation
$("form").validate({ submitHandler: viewModel.save });
表格标记为:
<table data-bind='visible: gifts().length > 0'>
<thead>
<tr>
<th>Gift name</th>
<th>Price</th>
<th>Tax</th>
<th />
</tr>
</thead>
<tbody data-bind='foreach: gifts'>
<tr>
<td><input class='required' data-bind='value: name, uniqueName: true' /></td>
<td><input class='required number' data-bind='value: price, uniqueName: true' /></td>
<td><input class='required number' data-bind='value: tax, uniqueName: true' /></td>
<td data-bind='text: formattedPrice'></td>
<td><a href='#' data-bind='click: $root.removeGift'>Delete</a></td>
</tr>
</tbody>
</table>
<button data-bind='click: addGift'>Add Gift</button>
<button data-bind='enable: gifts().length > 0' type='submit'>Submit</button>
由于formattedPrice 函数似乎无法正常工作,它正在停止。
我在这里找到了一个 jsfiddle:http://jsfiddle.net/marktait/TR6Sy/ - 谁能帮我克服这个看似简单的障碍?
谢谢,
标记
【问题讨论】:
标签: javascript jquery knockout.js