23

I need to update an observable array element value. The observable array is a collection of class objects. First I need to find out matching object by id and update some other property values of the object.

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

Can anyone suggest the approach of updating the view model? Let's say I want to update booked value to "false" for the seat no 2.

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

2 Answers 2

34

That's pretty simple with knockout:

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

3
  • 6
    what happens when you have multiple properties to be set? like here we only have seat.Booked, incase of multiple properties I would like to use ko.mapper plugin, is there a way to do that?
    – tusharmath
    Commented Jul 31, 2012 at 16:28
  • 8
    You can use the knockout's replace function to update the entire item: this.seats.replace(seat, newSeat);
    – jesal
    Commented May 6, 2014 at 18:00
  • I need more information on how the query is generated to the server (I guess the item has some ID), and what data the service returns (rest?)
    – Jorgelig
    Commented Jun 9, 2017 at 19:14
-9
viewModel.seats()[self.No()].Booked(true);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.