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.

4
  • Is there a reason the array isn't an observablearray? Commented Feb 18, 2013 at 0:41
  • possible duplicate of Knockout binding doesn't update using array of simple observables Commented Feb 18, 2013 at 2: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. Commented Feb 18, 2013 at 3:58
  • @AndrewWhitaker: This does seem to be the same issue; is there a good way to mark them as related? Commented Feb 18, 2013 at 3:58

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.