knockout checked binding doesn't update

房东的猫 提交于 2019-11-28 09:36:07

问题


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:


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>


来源:https://stackoverflow.com/questions/41267467/knockout-checked-binding-doesnt-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!