0

Note: This is not a question about ObservableArrays.

Let's say I have the following viewmodel:

var viewmodel = {
    arrayOfBooleans: [
        ko.observable(false),
        ko.observable(false),
        ko.observable(false)
    ]
}

And a view like so:

<div data-bind="foreach: arrayOfBooleans">
    <button data-bind="click: ????">Set to true</button>
</div>

What can I do inside the foreach to get the <button> to set the observable to true when clicked? Using data-bind="click: someFunction", the first argument someFunction gets is the unwrapped values of observables in the array (not the observables themselves), and seemingly no way to get back at the observables or to pass custom arguments.

Impirator
  • 1,393
  • 1
  • 12
  • 24
  • Is there a reason the array isn't an `observablearray`? – Kyeotic Feb 18 '13 at 00:41
  • possible duplicate of [Knockout binding doesn't update using array of simple observables](http://stackoverflow.com/questions/10621008/knockout-binding-doesnt-update-using-array-of-simple-observables) – Andrew Whitaker Feb 18 '13 at 02:08
  • @Tyrsius: Unfortunately, ObservableArrays are used to detect changes to the order or membership of the array, not manage the state of their members. For this situation, I don't care to notify anything about changes to the array itself. – Impirator Feb 18 '13 at 03:58
  • @AndrewWhitaker: This does seem to be the same issue; is there a good way to mark them as related? – Impirator Feb 18 '13 at 03:58

1 Answers1

1

Hope it will give some idea .

var viewmodel = {
  var self = this;
 self.arrayOfBooleans = ko.observableArray([]);

 self.arrayOfBooleans.push(new _newBoolean());
 self.arrayOfBooleans.push(new _newBoolean());
 self.arrayOfBooleans.push(new _newBoolean());

 function _newBoolean() { 
   self.one = ko.observable(false);
 }

self.setToTrue = function(index){
   self.arrayOfBooleans()[index].one(true);
 };
 }

If you want it as button

<div data-bind="foreach: arrayOfBooleans">
  <button data-bind="click: $root.setToTrue($parent.arrayOfBooleans.indexOf($data))"> 
   Set to true
  </button>
  <input type=hidden data-bind="value:one" />
</div>

If you want it as radio button than it is much more simple

<div data-bind="foreach: arrayOfBooleans">
  <span>Set To True</span><input type=radio data-bind="value:one" />
</div>

If you like this..Please Click uplink *or* If it solves your problem .. Mark this as answer

NaveenKumar1410
  • 1,565
  • 14
  • 20
  • 1
    Not a bad way to go, Boss. I think the simpler solution is posted in [Knockout binding doesn't update using array of simple observables](http://stackoverflow.com/questions/10621008/knockout-binding-doesnt-update-using-array-of-simple-observables). – Impirator Feb 18 '13 at 21:14