gpt4 book ai didi

javascript - KnockOut 的计算函数问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:49:59 25 4
gpt4 key购买 nike

使用 KnockOut - 我试图在添加到 MVC .Net 代码之前构建主细节/项目应用程序的基础。

我只想拥有一个简单的商品、价格、税金 - 以及一个计算列来显示每个商品的含税金额:

客户端 KnockOut View 模型是:

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/ - 谁能帮我克服这个看似简单的障碍?

谢谢,

标记

最佳答案

问题是您在循环礼物列表时调用了 comouted 函数。但是,计算方法不是对给定的礼物可用,而是对所有礼物都可用。您有两个选择:

要么使每个礼物对象成为具有此计算方法的对象(如用户 Brandon 所建议的那样),要么将其转换为以礼物作为参数的普通函数,如下所示:

self.getFormattedPrice = function(price, tax) {
var val = price ? "$" + parseFloat(price).toFixed(2) * (1 + tax) : "None";
return val;
};

然后,你可以这样调用它:

<td data-bind='text: $parent.getFormattedPrice(price, tax)'></td>

我已经更新了你的 fiddle .

关于javascript - KnockOut 的计算函数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16544144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com