简体   繁体   中英

Knockout.js two-way binding for checkbox not working

I'm new to knockout.js and I have some trouble with two-way binding of a checkbox.

I have a table that's bound to a list of "companies".

<table>
    <thead>
        <tr>
            <th>...</th>
            <th>...</th>
            <th>...</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: companies">
        <tr>                
            <td>...</td>
            <td><input type="checkbox" data-bind="checked:isCompanyForCommunication, click:$root.checkedNewCompanyForCommunication" /></td>
            <td>...</td>
        </tr>
    </tbody>
</table>

But there should only be 1 company with isCompanyForCommunication = true in the table. So when another checkbox is checked, I have to set all other companies to isCompanyForCommunication = false . Therefore I created a method in the viewModel to uncheck all other companies.

    // Definition of Company
    var Company = function (crmAccountObject, contactId, companyForCommunicationId) {

        this.isCompanyForCommunication = ko.observable(false);
    }

    // Definition of the ViewModel
    var ViewModel = function () {
        var self = this;

        // ...

        // Lists
        this.companies = null; // This observableArray is set somewhere else

        // Events
        this.checkedNewCompanyForCommunication = function (company, event) {

            // Set all companies to False
            for (var i = 0; i < self.companies().length; i++) {
                self.companies()[i].isCompanyForCommunication = ko.observable(false);
            }

            // Set the "checked" company to TRUE
            company.isCompanyForCommunication = ko.observable(true);
            return true;
        }
    }

However, the changes are not reflected in the HTML page. All other checkboxes remain checked.

I created a simplyfied example in jsfiddle to show what exactly I want to achieve with the checkbox https://jsfiddle.net/htZfX/59/

Someone has any idea what I'm doing wrong? Thanks in advance!

You are not setting the value of the isCompanyForCommunication but overriding it with a new observable.

Observables are functions and to update them you need to call them with the new value as the argument:

this.checkedNewCompanyForCommunication = function (company, event) {

            // Set all companies to False
            for (var i = 0; i < self.companies().length; i++) {
                self.companies()[i].isCompanyForCommunication(false);
            }

            // Set the "checked" company to TRUE
            company.isCompanyForCommunication(true);
            return true;
        }

I've also updated your sample code: JSFiddle .

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