knockout checked binding doesn't update

1.4k views Asked by At

I have list of objects I can select. I made a select all checkbox to click which selects all. The selecting works, but it doesn't update the checkbox value itself. Also, deselecting doesn't work, because the value is never true.

//html
<input type="checkbox" data-bind="checked: selecAllBT, click: selectAll" /> Select all
//other stuff

//JS
    self.selecAllBT = ko.observable(false);

    self.selectAllBodyTypes = function (self) {
     for (i = 0; i < self.items().length; i++) {
        if (self.selecAllBT() != self.items()[i].selected()){
            self.toggleSelected(self.items()[i]);
        }
    }
    self.selecAllBT(!self.selecAllBT);

    return true;

   }

I put it in a JSFiddle: https://jsfiddle.net/5mquej1f/21/ (I actually reused a JSFiddle from another issue of me, in case somebody recognizes it: knockout observablearray in 2 templates)

Anyone an idea what I'm doing wrong? thx

1

There are 1 answers

0
user3297291 On

You're implementing the same functionality twice:

The checkbox has toggle behaviour by default, implemented by your browser. Knockout plugs in to this functionality using the checked binding. You pass it an observable, and the value is stored:

var VM = function() {
  this.selectAllBT = ko.observable(false);
};

ko.applyBindings(new VM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<label>
  <input type="checkbox" data-bind="checked: selectAllBT" />toggle
</label>
<div>
  Value: <span data-bind="text: selectAllBT"></span>
</div>

The problem

Now, you've also included a click binding. This binding listens to a click on any element. In your click listener, you toggle the value by:

self.selecAllBT(!self.selecAllBT);

Then, you return true, passing the event to the checkbox. The checkbox will change naturally, and bound value will toggle again, changing it back to the old value.

Solution

A better way of implementing this, is removing the click listener and adding a subscribe to your checkbox value in the code behind:

var VM = function() {
  this.selectAllBT = ko.observable(false);
  
  this.doSomethingElse = function(selectAllValue) {
    console.log("Do work for new selectAll state:", selectAllValue);
  }
  
  this.selectAllBT.subscribe(this.doSomethingElse, this);
};

ko.applyBindings(new VM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<label>
  <input type="checkbox" data-bind="checked: selectAllBT" />toggle
</label>