Checked始终评估为false

时间:2017-03-16 20:33:44

标签: javascript knockout.js



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;
&#13;
&#13;

切换功能handleOnClick已损坏。无论如何,复选框仍保持选中状态。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

如果您使用带有复选框的click绑定,则使用您的处理程序must return true,以便您不会阻止默认操作(切换复选框)。

但一般来说,不需要在复选框上使用click绑定。只需使用checked即可。

&#13;
&#13;
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;
&#13;
&#13;