Knockout.js我应该如何将计算值添加到observaleArray中

Knockout.js How should I add computed value to observaleArray?

本文关键字:添加 observaleArray 计算 js 我应该 Knockout      更新时间:2024-04-09

我需要添加到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