单击绑定以使复选框在Knockout中无法正常工作

Los*_*ost 3 javascript jquery knockout.js

我有一个复选框和文本框.我希望textbox为空,并且每当选中复选框时都不可编辑.

在取消选择文本框时我必须禁用文本框的部分工作正常但是清空部分不能正常工作,因为我必须使用复选框的单击绑定,并且一旦我使用单击绑定,它就会打破复选框行为并且它变为不可点击.我有一个jsFiddle:http://jsfiddle.net/qK5Y3/16/

和下面的代码示例:

<input type="checkbox" id="emailTemplateSendAtTime" name="emailTemplateSendAtTime" data-bind="checked:SendAtTime, click:ClickSendAtTime"/>
<input type="text" style="width: 250px" id="emailTemplateSendAtTimeProperty" data-bind="value: SendAtTimeProperty, enable:SendAtTime"/>
Run Code Online (Sandbox Code Playgroud)

这是我的js:

var ViewModel = function () {

    this.SendAtTimeProperty = ko.observable("Something");
    this.SendAtTime = ko.observable();



    this.ClickSendAtTime = function () {
                if (model.SendAtTime() == false) {
                    model.SendAtTimeProperty("");
                }
            };
};
ko.applyBindings(new ViewModel());
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Cla*_*edi 8

两件事情:

  • 添加model为参数ClickSendAtTime
  • 返回true ClickSendAtTime以避免取消事件

    var ViewModel = function () {
    
        this.SendAtTimeProperty = ko.observable("Something");
        this.SendAtTime = ko.observable();
    
        this.ClickSendAtTime = function (model) {
                if (model.SendAtTime() == false) {
                    model.SendAtTimeProperty("");
                }
                return true;
            };
    };
    
    ko.applyBindings(new ViewModel());
    
    Run Code Online (Sandbox Code Playgroud)

另一种定义方式 ClickSendAtTime

this.ClickSendAtTime = function () {
      if (this.SendAtTime() == false) {
          this.SendAtTimeProperty("");
      }
      return true;
};
Run Code Online (Sandbox Code Playgroud)

有关您需要返回true的原因的一些信息

允许默认操作

默认情况下,Knockout将阻止事件采取任何默认操作.例如,如果使用事件绑定来捕获输入标记的keypress事件,则浏览器将仅调用处理函数,并且不会将键的值添加到input元素的值.一个更常见的例子是使用click绑定,它在内部使用此绑定,您的处理程序函数将被调用,但浏览器不会导航到链接的href.这是一个有用的默认值,因为当您使用点击绑定时,通常是因为您使用链接作为操纵视图模型的UI的一部分,而不是作为到另一个网页的常规超链接.

但是,如果您确实要继续执行默认操作,只需从事件处理函数返回true即可.

http://knockoutjs.com/documentation/event-binding.html