javascript knockout.js

javascript - Actualización del valor del elemento de matriz observable Knockout.js



(2)

Necesito actualizar un valor de elemento de matriz observable. La matriz observable es una colección de objetos de clase. Primero necesito averiguar el objeto coincidente por ID y actualizar algunos otros valores de propiedad del objeto.

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 "falso" para el asiento no 2.

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


Eso es bastante simple con un golpe de gracia:

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