function AppViewModel() {
var thisModel = this;
thisModel.handleOnClick = function() {
console.log('checked: ', thisModel.settings.checked());
//console.log('new value: ', newValue);
if(thisModel.settings.checked() === "checked"){
thisModel.settings.checked(null);
}else{
thisModel.settings.checked("checked");
}
};
thisModel.settings = {
checked: ko.observable("checked"),
onClick: thisModel.handleOnClick
};
return thisModel;
}
ko.applyBindings(new AppViewModel());

<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="checkbox" data-bind="checked: settings.checked, click: settings.onClick">
&#13;
切换功能handleOnClick
已损坏。无论如何,复选框仍保持选中状态。我在这里做错了什么?
答案 0 :(得分:1)
如果您使用带有复选框的click
绑定,则使用您的处理程序must return true
,以便您不会阻止默认操作(切换复选框)。
但一般来说,不需要在复选框上使用click
绑定。只需使用checked
即可。
function AppViewModel() {
var thisModel = this;
thisModel.settings = {
checked: ko.observable(true),
};
thisModel.settings.checked.subscribe(function (value) {
console.log("checked: " + value);
});
return thisModel;
}
ko.applyBindings(new AppViewModel());
&#13;
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="checkbox" data-bind="checked: settings.checked">
&#13;