Knockout Checked Binding Doesn't Update
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, deselectin
Solution 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:
varVM = function() {
this.selectAllBT = ko.observable(false);
};
ko.applyBindings(newVM());
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script><label><inputtype="checkbox"data-bind="checked: selectAllBT" />toggle
</label><div>
Value: <spandata-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:
varVM = 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(newVM());
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script><label><inputtype="checkbox"data-bind="checked: selectAllBT" />toggle
</label>
Post a Comment for "Knockout Checked Binding Doesn't Update"