I am quite new to knockoutjs and I am trying to create two toggles. When toggle one is switched off and then toggle two is switched off by the user, toggle one should be switched on and vice versa.
function alternatetogglesWithOrWithoutCreditRequests() {
if (!viewModel.withPendingCreditRequests()) {
viewModel.withoutPendingCreditRequests(true)
}
else if (!viewModel.withoutPendingCreditRequests()) {
viewModel.withPendingCreditRequests(true)
}
}
This code above does not work all the time because in both cases the withPendingCreditRequests
and the withoutPendingCredit
observables are false. The first statement will always be run in this scenario and it will not reach the else if statement.
Below is the HTML for the toggles:
<div>
<toggle-switch params="enable: invoiceFiltersActive, checked: withPendingCreditRequests, label: 'With Pending Credit Requests'">
</toggle-switch>
</div>
<div>
<toggle-switch params="enable: invoiceFiltersActive, checked: withoutPendingCreditRequests, label: 'Without Pending Credit Requests'">
</toggle-switch>
</div>
2
Answers
If anyone else is trying to still figure it out, I managed to find a way to make it work. On the html I have added data-bind to methods that handle clicks.
And on the view-model I have created those two methods with the following logic
Knockout has the ability to subscribe to observables, so you can watch for changes. That would be a cleaner approach:
You can see it in action here.