将真/假绑定到 Knockout JS 中的单选按钮 [英] Binding true / false to radio buttons in Knockout JS
问题描述
在我的视图模型中,我有一个 IsMale 值,其值为 true 或 false.
In my view model I have a IsMale value that has the value true or false.
在我的 UI 中,我希望将其绑定到以下单选按钮:
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>
我认为的问题是 checked
需要字符串true"/false".所以我的问题是,如何使用此 UI 和模型获得这种 2 向绑定?
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?
推荐答案
一种选择是使用 可写的计算 observable.
在这种情况下,我认为一个不错的选择是使可写的计算 observable 成为 IsMale
observable 的sub-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
});
};
您可以将它绑定到您的 UI 中,例如:
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>
示例:http://jsfiddle.net/rniemeyer/Pjdse/
这篇关于将真/假绑定到 Knockout JS 中的单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!