Knockout.js我应该如何将计算值添加到observaleArray中
Knockout.js How should I add computed value to observaleArray?
我需要添加到observableArray计算值,我当前的代码如下:
self.prices = ko.observableArray();
.....
var pax = $("select#ticketsnumber option:selected").val();
var irt;
if ($("input[name='isrt']").is(":checked")) {
irt = 1;
} else {
irt = 0;
}
$.each(self.prices(), function (price) {
price.FinalPrice = ko.computed(function() {
return prices.Price * irt * parseInt(pax);
});
});
但我不知道我应该如何调用这个计算值的绑定(目前是这样的-<span name="totalprice" data-bind="text: ko.utils.unwrapObservable($data.FinalPrice)">
),因为这似乎只是计算值没有添加——绑定结果显示0。数据模型:
public class PriceItem
{
...
public string Price { get; set; }
...
public int FinalPrice { get; set; }
}
这是我检索数据到self.prices:的方式
self.getprices = function () {
var destinationtypefrom = $("select#optionsfrom option:selected").attr("name");
var destinationtypeto = $("select#optionsto option:selected").attr("name");
var fromcode = $("select#optionsfrom").val();
var tocode = $("select#optionsto").val();
var json = { desttypefrom: destinationtypefrom, desttypeto: destinationtypeto, codefrom: fromcode, codeto: tocode, 'DepartureDate': $("#departure").val(), 'ReturnDate': $("#return").val() };
$.ajax({
url: "/Home/GetFlights",
data: json,
type: "post",
cache: false,
success: function (result) {
if (result.Error == null) {
self.prices(result);
ko.mapping.fromJS(result, {}, self.prices);
} else {
$("#modalerror").on("show.bs.modal", function () {
var modal = $(this);
modal.find("#errormsg").text(result.Error);
});
}
},
error: function (xhr) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
主要问题是$.each
假设第一个参数是prices
数组中的实际元素是错误的。事实上,第一个参数是索引,第二个参数是要扩充的实际price
。
此外,您在computed
函数计算中似乎有一个拼写错误,它是price.Price
而不是prices.Price
。
试试这个:
$.each(self.prices(), function (index, price) {
price.FinalPrice = ko.computed(function() {
return price.Price * irt * parseInt(pax);
});
});
在你的HTML中,类似于:
<div data-bind="foreach: prices">
<span name="totalprice" data-bind="text: FinalPrice"></span>
</div>
请参阅Fiddle
相关文章:
- 正在添加'X'按钮,在文本字段旁边使用javascript
- 如何在映射数组中添加换行符
- 正在将数据主题添加到所有项目
- ZeroClipboard-在复制之前添加到值
- 我可以在json对象中添加一个函数吗
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 正在SharePoint 2013母版页中添加JQuery移动文件
- 如何添加浮动和非浮动,其他
- 添加文字和评论功能更新Div
- 如果使用 lodash 将属性存在于另一个对象中,则向对象添加属性
- 动态地改变“”的URL;添加新项目”;链接使用javascript/jquery
- 在函数中添加数组元素的数值
- 如何将歌曲添加到jPlayer
- 在html Select中添加搜索
- Java脚本时间添加
- FabricJs-限制主对象内添加对象的移动区域
- JQuery添加元素需要在我的js之前再次添加JQuery脚本
- 如何在Google柱状图中动态添加行/列
- 正在尝试使用if和else添加类,但无法正常工作
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象