更新Knockout.js可观察的数组元素值

Bra*_*ild 23 javascript knockout.js

我需要更新一个可观察的数组元素值.可观察数组是类对象的集合.首先,我需要通过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)
    ] )
};
Run Code Online (Sandbox Code Playgroud)

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

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

Nik*_*iko 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);
}
Run Code Online (Sandbox Code Playgroud)

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

  • 您可以使用knockout的replace函数来更新整个项目:`this.seats.replace(seat,newSeat);` (8认同)
  • 当您要设置多个属性时会发生什么?像这里我们只有seat.Booked,多个属性我想使用ko.mapper插件,有没有办法做到这一点? (6认同)