当另一个值更改时,如何更新一个绑定值?

时间:2012-12-17 16:16:37

标签: knockout-2.0

我有一个smiple选择控件绑定到包含2个值的模型:id - 我想绑定到选定索引的值,而cities =数组我想要填充的ooptions。 这是JS:

    var VM=function ViewModel() {
      self=this;


        this.id = ko.observable(102);
        this.cities=ko.observableArray([]); 

        this.getCities=function(){ 
              self.cities( [{"Key":"-1","Value":"choose city"},{"Key":"100","Value":"leningrad"},   {"Key":"102","Value":"moscow"}]); 
        } ;
    }

    var vm=new VM();
    ko.applyBindings(vm);

我希望用户点击按钮后可以播放城市,但所选城市必须留在莫斯科(因为最初“id”为102)

这是我的HTML:

    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://cloud.github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
    <meta charset=utf-8 />
    <title>JS Bin</title>
    </head>
    <body>
      <select data-bind="options:cities,optionsText:'Value',optionsValue:'Key',value:id"></select>

      <button data-bind="click:getCities">get cities</button>
    </body>
    </html>

我的问题是城市加载后所选索引丢失了 请帮忙 感谢

1 个答案:

答案 0 :(得分:0)

我想出了我的问题所在: 'value'绑定是双向的,所以当首先绑定选择没有选项时 - 'id'变为-1。 当我改为:

  <select data-bind="options:cities,optionsText:'Value',optionsValue:'Key'"></select>

并补充说:

    this.getCities=function(){ 
          self.cities( [{"Key":"-1","Value":"choose city"},{"Key":"100","Value":"leningrad"},   {"Key":"102","Value":"moscow"}]
                     ); 


      $('select').val(self.id());
    } ;

事情开始奏效了, 但现在问题是如果用户在选择填充后选择某个城市时如何收集价值: 我的解决方案是将选择更改附加到不显眼的jquery处理程序:

          var VM=function ViewModel() {
          self=this;


            this.id = ko.observable(102);
            this.cities=ko.observableArray([]); 

            this.getCities=function(){ 
                  self.cities( [{"Key":"-1","Value":"choose city"},{"Key":"100","Value":"leningrad"},   {"Key":"102","Value":"moscow"}]
                             ); 


              $('select').val(self.id());
            } ;



        };
    var f=function(){
      vm.id($('select').val())



    }
        var vm=new VM();
        ko.applyBindings(vm);
    $('select').change(f)

我希望它会帮助那些遇到我问题的人......

相关问题