Reputation: 1304
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>
Upvotes: 0
Views: 315
Reputation: 566
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);
};
Upvotes: 2