2013-04-06 41 views
9

名称+复选框的单向绑定工作正常,但它对单选按钮employeeTypeA不起作用,尽管其值在viewmodel中为true html显示单选按钮没有设置,为什么?淘汰赛没有在单选按钮上设置初始真实值

<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> 

回答

8

checked绑定工作,不同的单选按钮,从文档:

单选按钮,KO就会将元素进行检查,当且仅当参数值等于单选按钮节点value属性。

所以,你需要你的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属性,你可以介入UCE返回的类型计算的属性:

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.

+0

我检查了knockoutJS现场,看着教程:wantsSpam:ko.observable(真),但我没有看到wantsSpam绑定到visibility属性...不是直接的单选按钮。 正如你也知道ASP.NET MVC会不会是一个更好的主意,考虑这个布尔在服务器端viewmodel字符串'转换器'无论看起来像什么?! – Elisabeth 2013-04-06 19:53:25

+0

当我把你的最后一个代码块放到我的visual studio html文件中时,我得到2个错误/警告:可疑的使用这个运算符,并不是所有的代码路径都返回一个值。 – Elisabeth 2013-04-06 20:02:57

+0

我的另一个问题是为什么你有这样做:“this.employeeTypeA()”,而不是“this.employeeTypeA”。至于我的JavaScript初学者知识去employeeType是一个属性,但你像一个函数调用?这是没有批评只是一个好奇的问题:) – Elisabeth 2013-04-06 20:18:09