检查Knockout.js复选框并单击事件

Dav*_*eid 5 checkbox knockout.js

我们正在尝试使用以下功能实现复选框和列表:

  • 单击该复选框将清除阵列(如果有项目),或者如果没有则添加新项目.
  • 单击"删除"按钮时从阵列中删除项目,删除最后一项后,复选框会自动取消选中.

我遇到的问题是,如果你单击删除每个数组项,然后单击复选框添加一个空白条目,我希望再次检查复选框(根据已检查的observable),但它不是?

我有以下代码:

http://jsfiddle.net/UBsW5/3/

    <div>
        <input type="checkbox" data-bind="checked: PreviousSurnames().length > 0, click: $root.PreviousSurnames_Click" />Previous Surname(s)?
    </div>
    <div data-bind="foreach: PreviousSurnames">
        <div>
            <input type="text" data-bind="value: $data">
            <span data-bind="click: $root.removePreviousSurname">Remove</span>
        </div> 
    </div>


var myViewModelExample = function () {
    var self = this;

    self.PreviousSurnames = ko.observableArray(['SURNAME1', 'SURNAME2', 'SURNAME3']);

    self.removePreviousSurname = function (surname) {
        self.PreviousSurnames.remove(surname);
    };

    self.PreviousSurnames_Click = function () {
        if (self.PreviousSurnames().length === 0) {
            self.PreviousSurnames.push('');
        }
        else {
            self.PreviousSurnames.removeAll();
        }
        alet(2)
    }

}

ko.applyBindings(new myViewModelExample());
Run Code Online (Sandbox Code Playgroud)

nem*_*esv 16

如果您正在一起使用click,checked那么您需要return true从单击处理程序中允许浏览器默认单击操作,在这种情况下检查复选框:

self.PreviousSurnames_Click = function () {
    if (self.PreviousSurnames().length === 0) {
        self.PreviousSurnames.push('');
    }
    else {
        self.PreviousSurnames.removeAll();
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

演示JSFiddle.


Dav*_*ast 5

您需要使用计算来监视可观察数组的长度。这样,当长度达到零时,您可以自动对其做出反应。

    self.surnames = ko.computed(function() {
        var checked = true;
        if (self.PreviousSurnames().length === 0) {
            self.PreviousSurnames.push('');
            checked = false;
        }            
        return checked;
    });
Run Code Online (Sandbox Code Playgroud)

现在,清除所有名称后,您将拥有空白文本框。如果您更新复选框上的绑定,它也会正常运行。

<input type="checkbox" data-bind="checked: surnames, click: PreviousSurnames_Click" />Previous Surname(s)?
Run Code Online (Sandbox Code Playgroud)

小提琴