简体   繁体   中英

KnockoutJS Observable not updating in template

I have a toggle on a span where the class updates in Knockout JS. When I log out the value of the Observable, it is correct. However, the class of the checkbox doesn't toggle as expected. Here is the JS and template code I am using...

JS

viewModel.toggleRequiredAnswer = function(self, index) {
    // Other unrelated code using index param here
  var checkedTest = viewModel
      .data()
      .conditionalRequired.requiredIf.some(function(arr) {
        return arr === index;
    });
    self.isChecked = ko.observable(checkedTest);
};

KnockoutJS template

<ul class="list" data-bind="foreach: list">
    <li>
        <span
          class="glyphicon glyphicon-admin"
          data-bind="
                    click: $parent.toggleRequiredAnswer($data, $data.value),
                    css: $data.isChecked() ? 'glyphicon-check' : 'glyphicon-unchecked'"
        >
            </span>
        <span data-bind="text: $data.text"></span>
    </li>
</ul>

When the function toggleRequiredAnswer is clalled you overwrite the self.isChecked attribute with a new observable and the knockout view is loosing the relationship to it. The function toggleRequiredAnswer should look something like this:

viewModel.toggleRequiredAnswer = function(self, index) {
    // Other unrelated code using index param here
  var checkedTest = viewModel
      .data()
      .conditionalRequired.requiredIf.some(function(arr) {
        return arr === index;
    });
    self.isChecked(checkedTest);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM