在knockout JS中计算得到observableArray索引

时间:2014-08-07 10:02:35

标签: knockout.js

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

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());
    });

1 个答案:

答案 0 :(得分:1)

您最好使用$index。示例2显示了如何执行此操作: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>