将真/假绑定到Knockout JS中的单选按钮 [英] Binding true / false to radio buttons in Knockout JS

查看:129
本文介绍了将真/假绑定到Knockout JS中的单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的视图模型中,我有一个值为true或false的IsMale值。



在我的UI中,我希望将它绑定到以下单选按钮:

 < label>男性
< input type =radioname =IsMalevalue =true数据绑定= 选中:IsMale/>
< / label>
< label>女
< input type =radioname =IsMalevalue =falsedata-bind =checked:IsMale/>
< / label>

我认为问题是已检查预计会出现问题字符串true/false。所以我的问题是,我怎样才能获得这个具有这个UI和模型的双向绑定?

解决方案

一个选项是使用可写的计算可观察量



<在这种情况下,我认为一个不错的选择是使可写的计算的observable成为 IsMale observable的sub-observable。您的视图模型如下所示:

  var ViewModel = function(){
this.IsMale = ko.observable(真正);

this.IsMale.ForEditing = ko.computed({
read:function(){
return this.IsMale()。toString();
},
写:function(newValue){
this.IsMale(newValue ===true);
},
owner:this
});
};

你可以在你的用户界面中绑定它,如:

 < label>男性
< input type =radioname =IsMalevalue =truedata-bind =checked:IsMale.ForEditing />
< / label>
< label>女
< input type =radioname =IsMalevalue =falsedata-bind =checked:IsMale.ForEditing/>
< / label>

示例: http://jsfiddle.net/rniemeyer/Pjdse/


In my view model I have a IsMale value that has the value true or false.

In my UI I wish to bind it to the following radio buttons:

<label>Male
   <input type="radio" name="IsMale" value="true" data-bind="checked:IsMale"/>
</label> 
<label>Female
   <input type="radio" name="IsMale" value="false" data-bind="checked:IsMale"/>
</label>

The problem I think is checked expects a string "true" / "false". So my question is, how can I get this 2-way binding w/ this UI and model?

解决方案

One option is to use a writeable computed observable.

In this case, I think that a nice option is to make the writeable computed observable a "sub-observable" of your IsMale observable. Your view model would look like:

var ViewModel = function() {
   this.IsMale = ko.observable(true);

   this.IsMale.ForEditing = ko.computed({
        read: function() {
            return this.IsMale().toString();  
        },
        write: function(newValue) {
             this.IsMale(newValue === "true");
        },
        owner: this        
    });          
};

You would bind it in your UI like:

<label>Male
   <input type="radio" name="IsMale" value="true" data-bind="checked:IsMale.ForEditing"/>
</label> 
<label>Female
   <input type="radio" name="IsMale" value="false" data-bind="checked:IsMale.ForEditing"/>
</label>

Sample: http://jsfiddle.net/rniemeyer/Pjdse/

这篇关于将真/假绑定到Knockout JS中的单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆