lundi 27 novembre 2017

KnockoutJS Binding a checkbox with both "checked" and "click" bindings causes unexpected behavior

here is the code I've been working on.

Javascript:

function ViewModel() {
  var self = this;

    self.isChecked = ko.observable(false);

  self.testing = function(){
    console.log("hello from testing");
  }
}

var app = new ViewModel();

ko.applyBindings(app);

And here's the html:

<div>
  <div>
    <button data-bind="click: testing" type="button">Something</button>
    <input data-bind="checked: isChecked, click: testing" type="checkbox" />
    <input data-bind="checked: isChecked" type="checkbox" />
  </div>
</div>

What I'm looking to accomplish is that I want a checkbox, whose value is data-binded to a variable in my model and updates accordingly. And at the same time, whenever a user clicks the checkbox to change its boolean value, I want a function to be executed AFTER the value is changed in the model and the checkbox is updated.

I have two buttons data-binded to the same value just for testing purposes. When I click the checkbox that is binded with click to testing, its value doesn't update, but the function executes correctly. However, the other checkbox DOES indeed update to reflect the changes in the model when the button is clicked.

What is happening that causes this behavior, and how could I write a better solution to achieve what I'm looking for?




Aucun commentaire:

Enregistrer un commentaire