Knockout绑定选择到单选按钮

时间:2017-01-13 21:30:36

标签: knockout.js radio-button

我想说:

function viewModel(){
    this.mySelect=ko.observable();
    this.myRadio=ko.observable();
};
ko.applyBindings(new ViewModel());

<select data-bind="value: mySelect">
    <option>select you language</option>
    <option value="English">English</option>
    <option value="French">French</option>
    <option value="Italian">Italian</option>
</select>

Need translator:
<input type="radio" name="needTransaltor" value="Y" data-bind="checked: myRadio">Yes
<input type="radio" name="needTransaltor" value="N" data-bind="checked: myRadio">No

我怎样才能: 如果用户从下拉菜单中选择“英语”,选中单选按钮“否”并为this.myRadio分配值“否”?

1 个答案:

答案 0 :(得分:0)

下面是一个可能的解决方案。使用单选按钮的已检查绑定和选择的选项绑定。然后对于select的值绑定我使用可写的计算可观察http://knockoutjs.com/documentation/computed-writable.html来改变单选按钮,如果用户选择英语。你可以运行下面的例子。选择除英语之外的语言,将需要翻译设置为是然后将语言更改为英语,单选按钮将更新为否。

function model() {
  var self = this;
  this.availableLanguages = ko.observableArray([
    'English',
    'French',
    'Italian'
  ]);
  this.needTranslator = ko.observable('N');
  this.language = ko.observable('');

  this.selectedLanguage = ko.pureComputed({
    read: function() {
      return this.language();
    },
    write: function(value) {
      if (value === 'English') {
        this.needTranslator('N');
      }
      this.language(value);
    },
    owner: this
  });


}

var mymodel = new model();

$(document).ready(function() {
  ko.applyBindings(mymodel);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>
  choose language:
  <select data-bind="options: availableLanguages,
value: selectedLanguage,          optionsCaption: 'Choose...'"></select>
</p>

Need Translator:
<div>
  <input type="radio" name="needTranslator" value="N" data-bind="checked: needTranslator" />No</div>
<div>
  <input type="radio" name="needTranslator" value="Y" data-bind="checked: needTranslator" />Yes</div>