Knockout.js双向绑定复选框无法正常工作

时间:2015-07-31 07:27:38

标签: javascript checkbox knockout.js binding

我是knockout.js的新手,我在复选框的双向绑定方面遇到了一些麻烦。

我有一张表格会被列入"公司&#34 ;.

<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>

但表中应该只有一家公司isCompanyForCommunication = true。因此,当选中另一个复选框时,我必须将所有其他公司设置为isCompanyForCommunication = false。因此,我在viewModel中创建了一个方法来取消选中所有其他公司。

    // 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;
        }
    }

但是,更改不会反映在HTML页面中。所有其他复选框仍保持选中状态。

我在jsfiddle中创建了一个简单的示例,通过复选框https://jsfiddle.net/htZfX/59/

显示我想要实现的目标

有人知道我做错了什么吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

您没有设置isCompanyForCommunication的值,而是使用新的observable覆盖它。

Observables是函数,要更新它们需要使用新值作为参数调用它们:

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;
        }

我还更新了您的示例代码:JSFiddle