敲除绑定到收音机盒

时间:2016-12-19 11:21:04

标签: javascript jquery html knockout.js

我有收音机盒。为此我已经绑定click事件。 问题:如果应该从开始检查这个收音机盒 - 它不是。

所以我想添加checked事件。但这会使click逻辑失效,所以它看起来像是双击。

如何在创建ViewModel时手动调用click,将所有事件正确绑定到无线电?

<input data-bind="css: { checked: $component.isActiveGroup(value) },
                              click: $component.setActiveGroup.bind($component, value), 
                              checked: $component.activeGroup"
                   value={{value}}
                   type="radio" />

setActiveGroup(groupName: string) {
    if (!groupName) {
        return;
    }
    const isActive = this.isActiveGroup(groupName);
    this.activeGroup(isActive ? '' : groupName);
}

isActiveGroup(groupName: string) {
    return this.activeGroup() === groupName;
}

activeGroup = ko.observable('');

1 个答案:

答案 0 :(得分:1)

checked绑定默认执行您需要的所有操作:

var VM = function() {

  this.activeGroup = ko.observable("A");
  this.activeGroup.subscribe(console.log.bind(console));

  this.isActiveGroup = groupName => {
    return this.activeGroup() === groupName;
  }


  this.groups = ["A", "B", "C"];
}


ko.applyBindings(new VM());
.checked { background: yellow; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<!-- ko foreach: groups -->
<label data-bind="css: { checked: $parent.isActiveGroup($data) }">
  <span data-bind="text: $data"></span>
  <input type="radio" data-bind="value: $data,
                                 checked: $parent.activeGroup" />
</label>
<!-- /ko -->

如果您正在寻找“切换”功能,则应创建type="checkbox"输入或创建其他选项none。无线电盒意味着每组有1个选择。

P.S。要对选中的输入进行样式设置,您还可以使用:checked css选择器。在我的例子中,我选择设置周围label的样式。

相关问题