本文介绍了获取在剔除JS中计算出的observableArray索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将GuestNumber字段与UI绑定,如何计算GuestNumber字段?

I want to bind GuestNumber field with UI how can I calculate GuestNumber field?

var GuestLine = function () {
        var self = this;
        self.FirstName = ko.observable();
        self.LastName = ko.observable();
        self.Email = ko.observable();
        this.GuestNumber = ko.computed(function() {
            return this.index;
        }, this);
    };


    var Cart = function () {
        // Stores an array of lines, and from these, can work out the grandTotal
        var self = this;
        self.Guests = ko.observableArray([new GuestLine()]); // Put one line in by default
        self.ParticipantFirstName = ko.observable();
        self.ParticipantLastName = ko.observable();
        self.ParticipantEmail= ko.observable();

        // Operations
        self.addLine = function () { self.Guests.push(new GuestLine()); };
        self.removeLine = function (line) { self.lines.remove(line); };
        self.save = function () {

            var dataToSave = ko.mapping.toJSON(self);

            $.ajax({
                type: 'POST',
                url: '/API/RSVPHandlerService.ashx',
                data: dataToSave,
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (r) {
                    alert(r.d.Name);
                    alert(r.d.Population);
                }
            });


        };
    };
    $(function () {
        ko.applyBindings(new Cart());
    });

推荐答案

最好使用$index.示例2显示了如何执行此操作: http://knockoutjs.com/documentation/foreach-binding.html

You are better using $index. Example 2 shows how to do this: http://knockoutjs.com/documentation/foreach-binding.html

<h4>People</h4>
<ul data-bind="foreach: people">
    <li>
        Name at position <span data-bind="text: $index"> </span>:
        <span data-bind="text: name"> </span>
        <a href="#" data-bind="click: $parent.removePerson">Remove</a>
    </li>
</ul>

这篇关于获取在剔除JS中计算出的observableArray索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 05:10