我需要更新一个可观察的数组元素值。
可观察数组是类对象的集合。
首先,我需要按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)
    ] )
};

谁能建议更新 View 模型的方法?
假设我想将2号座位的预订价格更新为“假”。

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

最佳答案

使用 knockout 非常简单:

// 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/

10-08 11:43