Search code examples
javascriptknockout.js

If toggle one is switched off and then toggle two is switched off by the users then toggle one should be switched on


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>

Solution

  • Knockout has the ability to subscribe to observables, so you can watch for changes. That would be a cleaner approach:

    function ViewModel() {    
        this.checkboxOne = ko.observable(false);
        this.checkboxTwo = ko.observable(false);
        
        this.checkboxOne.subscribe(newVal => {
            if (!newVal && !this.checkboxTwo()) {
                this.checkboxTwo(true);
            }
        });
        
        this.checkboxTwo.subscribe(newVal => {
            if (!newVal && !this.checkboxOne()) {
                this.checkboxOne(true);
            }
        });
    }
    

    You can see it in action here.