23

我需要更新一个可观察的数组元素值。可观察数组是类对象的集合。首先,我需要通过 id 找出匹配的对象并更新对象的一些其他属性值。

var Seat = function(no, booked) {
    var self = this;
    self.No = ko.observable(no);
    self.Booked = ko.observable(!!booked);

    // Subscribe to the "Booked" property
    self.Booked.subscribe(function() {
        alert( self.No() );
    });
};

var viewModel = {
    seats: ko.observableArray( [
        new Seat(1, false), new Seat(2, true), new Seat(3, true),
        new Seat(4, false), new Seat(5, true), new Seat(6, true),
        new Seat(7, false), new Seat(8, true), new Seat(9, true)
    ] )
};

任何人都可以建议更新视图模型的方法吗?假设我想将 2 号座位的预订价值更新为“false”。

http://jsfiddle.net/2NMJX/3/

4

2 回答 2

34

淘汰赛非常简单:

// We're looking for the Seat with this No 
var targetNo = 2;

// Search for the seat -> arrayFirst iterates over the array and returns the
// first item that is a match (= callback returns "true")!
var seat = ko.utils.arrayFirst(this.seats(), function(currentSeat) {
    return currentSeat.No() == targetNo; // <-- is this the desired seat?
});

// Seat found?
if (seat) {
    // Update the "Booked" property of this seat!
    seat.Booked(true);
}

http://jsfiddle.net/2NMJX/4/

于 2012-06-28T14:25:15.307 回答
-9
viewModel.seats()[self.No()].Booked(true);
于 2013-03-17T09:56:32.167 回答