簡體   English   中英

更新Knockout.js可觀察的數組元素值

[英]Updating Knockout.js Observable array element value

我需要更新一個可觀察的數組元素值。 可觀察數組是類對象的集合。 首先,我需要通過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號座位的預訂值更新為“假”。

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

淘汰賽非常簡單:

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

viewModel.seats()[self.No()].Booked(true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM