2012-06-28 23 views
23

観測可能な配列要素の値を更新する必要があります。 観測可能な配列は、クラスオブジェクトのコレクションです。 まず、idで一致するオブジェクトを探し、オブジェクトの他のプロパティ値を更新する必要があります。Knockout.jsの更新観測可能な配列要素の値

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.

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

答えて

35

ための "偽" に予約した値を更新したいとしましょう:

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

+6

何が起こりますかあなたは複数のプロパティを設定する必要がありますか?私たちはko.mapperプラグインを使用したい、複数のプロパティのincase、それを行う方法はありますか? – Tushar

+7

ノックアウトの置換機能を使って項目全体を更新することができます: 'this.seats.replace(seat、newSeat);' – jesal

+0

クエリがサーバーに生成される方法に関する詳細が必要です(アイテムにIDがあると思います) 、サービスが返すデータ(休憩) – Jorgelig

-8
viewModel.seats()[self.No()].Booked(true); 
関連する問題