Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Knockout.js Observable array element value

Tags:

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/

like image 895
Brainchild Avatar asked Jun 28 '12 14:06

Brainchild


People also ask

How do I change the value of an observable array?

You should look at defining the object structure for each element of your array and then add elements of that type to your observable array. Once this is done, you will be able to do something like item. productQuantity(20) and the UI will update itself immediately. EDIT Added the function provided by the OP :).

How do I set observable value in knockout?

To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.


1 Answers

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/

like image 69
Niko Avatar answered Sep 22 '22 04:09

Niko