0

我在使用 knockout.js 时遇到数据绑定复选框的问题。jsfiddle http://jsfiddle.net/sajesh1985/ypbLN/

(HTML)代码:

<h2>View1</h2>
<h4>Select Columns:</h4>
<ul data-bind="foreach: gridOptions.columns" data-role="listview">
<div data-role="fieldcontain" >
<li id="li">     
    <label>
        <input type="checkbox" id="chk" data-bind="event: {change: function(){ checked(!checked()); } }, checkbox: checked" /> <span data-bind="text: header"></span>
    </label>
</li>
</div>
</ul>
<hr>
<table>
<thead>
    <tr data-bind="foreach: gridOptions.columns">
        <th data-bind="visible:checked, text: header"></th>
    </tr>
</thead>
<tbody data-bind="foreach: people">
    <tr data-bind="foreach: $parent.gridOptions.columns">
        <td data-bind="text: $parent[dataMember], visible:checked"></td>
    </tr>
</tbody>
</table>

JS代码:

var ProductSearchViewModel = {

gridOptions: {
    columns: [{
        header: 'First Name',
        dataMember: 'firstName',
        checked: ko.observable(true)
    }, {
        header: 'Last Name',
        dataMember: 'lastName',
        checked: ko.observable(true)
    }]
},

people: [{
    firstName: 'Bert',
    lastName: 'Bertington'
}, {
    firstName: 'Charles',
    lastName: 'Charlesforth'
}, {
    firstName: 'Denise',
    lastName: 'Dentiste'
}]


};

ko.bindingHandlers.checkbox = {
update: function (element, valueAccessor) {

    var value = valueAccessor();

    var valueUnwrapped = ko.utils.unwrapObservable(value);

    //$(element).checkboxradio().trigger('create');               
    $(element).attr("checked", valueUnwrapped).checkboxradio("refresh");

}
};

$(document).ready(function () {
ko.applyBindings(ProductSearchViewModel);    
});

你能帮我纠正这个问题吗?我得到 Uncaught cannot call methods on checkboxradio 在初始化之前;试图在浏览器中调用方法“刷新”。

4

1 回答 1

0

绑定复选框的最佳方法是使用选中的绑定,如下所示:

<input type="checkbox" id="chk" data-bind="checked: checked" />

另请参阅文档: http: //knockoutjs.com/documentation/checked-binding.html

于 2013-04-27T20:51:01.957 回答