2012-06-28 9 views
23

Necesito actualizar un valor de elemento de matriz observable. La matriz observable es una colección de objetos de clase. Primero necesito encontrar el objeto coincidente por identificación y actualizar algunos otros valores de propiedad del objeto.Actualizando Knockout.js Valor de elemento de matriz observable

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) 
    ]) 
}; 

¿Alguien puede sugerir el enfoque de actualizar el modelo de vista? Digamos que quiero actualizar el valor reservado a "false" para el asiento sin 2.

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

Respuesta

35

Eso es bastante simple, con nocaut:

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

lo que sucede cuando tienes varias propiedades para establecer? como aquí, solo tenemos asiento. Reservado, en caso de propiedades múltiples me gustaría usar el plugin ko.mapper, ¿hay alguna manera de hacerlo? – Tushar

+7

Puede utilizar la función de sustitución de la eliminación para actualizar todo el elemento: 'this.seats.replace (seat, newSeat);' – jesal

+0

Necesito más información sobre cómo se genera la consulta en el servidor (supongo que el elemento tiene alguna ID) y qué datos devuelve el servicio (¿reposo?) – Jorgelig

-8
viewModel.seats()[self.No()].Booked(true); 
Cuestiones relacionadas