我正在构建一个 Knockout View 模型。该模型有一些字段,例如 dateFrom
、DateTo
、Status
等。此外,还有一个发票
列表。
发票包含一些定价信息,它是一个 price
对象。我的主要对象还有一个价格对象,它应该迭代所有发票对象并找到总价。
我的问题如下:
代码运行顺利,直到我在 View 中添加以下内容:
<label data-bind="text:totalPrice().price().priceExVat"></label>
这里我得到一个:
TypeError: $(...).price is not a function
指的是我的:
exVat += $(ele).price().priceExVat;
我不明白,因为在我的每个函数中,我应该有该元素。该元素有一个 price()
函数,那么为什么它不起作用呢?是范围问题吗?
我的 View 模型:
function invoice(invoiceDate, customerName, pdfLink, status) {
var self = this;
self.pdfLink = pdfLink;
self.print = ko.observable(0);
self.customerName = customerName;
self.status = status;
self.pdfPagesCount = function () {
return 1;
};
self.invoiceDate = invoiceDate;
self.price = function () {
return new price(1.8, 2.1);
};
}
function price(exVat, total) {
var self = this;
self.currency = '€';
self.total = total;
self.priceExVat = exVat;
self.vatPercentage = 0.25;
self.vatAmount = self.exVat - self.total;
self.priceExVatText = function() {
return self.priceExVat + ' ' + self.currency;
};
}
var EconomicsViewModel = function (formSelector, data) {
var self = this;
self.dateFrom = data.dateFrom;
self.dateTo = data.dateTo;
self.invoices = ko.observableArray([
new invoice('05-05-2014', 'LetterAmazer IvS', "http://www.google.com","not printed"),
new invoice('05-05-2014', 'LetterAmazer IvS', "http://www.google.com", "not printed")
]);
self.totalPrice = function () {
var exVat = 0.0;
$(self.invoices).each(function (index, ele) {
console.log(ele);
exVat += $(ele).price().priceExVat;
});
return price(exVat, 0);
};
};
最佳答案
据我所知,totalPrice
实际上是一个price
对象,您不需要放置.price()
:
<label data-bind="text:totalPrice().priceExVat"></label>
编辑:
抱歉,您的 JavaScript 也存在问题:
self.totalPrice = function () {
var exVat = 0.0;
$(self.invoices()).each(function (index, ele) { //<-- add () to self.invoices to get the array
console.log(ele);
exVat += ele.price().priceExVat; //<-- remove useless jQuery
});
return new price(exVat, 0); //<-- add 'new'
};
编辑2:
回复robert.westerlund的注释,您可以删除 $().each
并替换为 ko.utils.arrayForEach
或更简单地使用 for
循环:
var arr = self.invoices();
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
exVat += arr[i].price().priceExVat;
}
已更新 fiddle
关于javascript - 如何在 Knockout View 模型中的每个函数内迭代匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23709391/