knockout不会在单选按钮上设置初始真值

时间:2013-04-06 16:56:57

标签: knockout.js

名称+复选框的单向绑定工作正常,但它最初对于单选按钮employeeTypeA不起作用,尽管在viewmodel中它的值为true,html显示单选按钮未设置,为什么会这样? / p>

   <script type="text/javascript">

        $(function()
        {
            var PersonViewModel = function()
            {
                this.firstName = ko.observable('Lisa');
                this.lastName = ko.observable('T');
                this.isCustomer = ko.observable(true);
                this.employeeTypeA = ko.observable(true);
                this.employeeTypeB = ko.observable(false);
            };

            var personViewModel = new PersonViewModel();
            ko.applyBindings(personViewModel, $('data').get(0));
        });
    </script>

    <div id="data">
        <span data-bind="text: firstName"></span>
        <span data-bind="text: lastName"></span>
        <input type="checkbox" data-bind="checked: isCustomer" title="Is a customer" />
        <input name="x" type="radio" data-bind="checked: employeeTypeA" title="Employee type A" />
        <input name="x" type="radio" data-bind="checked: employeeTypeB" title="Employee type B" />
    </div>

1 个答案:

答案 0 :(得分:8)

checked绑定对于单选按钮的工作方式不同,来自文档:

  

对于单选按钮,当且仅当参数值等于单选按钮节点的value属性时,KO才会设置要检查的元素。

因此,您需要将PersonViewModel更改为以下内容:

var PersonViewModel = function()
{
    this.firstName = ko.observable('Lisa');
    this.lastName = ko.observable('T');
    this.isCustomer = ko.observable(true);
    this.employeeType = ko.observable('TypeB');                
};

你的收音机按钮:

<input name="x" type="radio" data-bind="checked: employeeType" 
       value="TypeA" title="Employee type A" />
<input name="x" type="radio" data-bind="checked: employeeType" 
       value="TypeB" title="Employee type B" />

演示JSFiddle.

如果要保留employeeTypeAemployeeTypeB属性,可以引入一个返回类型的计算属性:

this.employeeTypeA = ko.observable(false);
this.employeeTypeB = ko.observable(true);
this.employeeType = ko.computed(function()
{
     if (this.employeeTypeA())
        return 'TypeA';
     if (this.employeeTypeB())
        return 'TypeB';
},this);  

同样在这种情况下,您需要在单选按钮上添加value属性。

演示JSFiddle.