0

I have a smiple select control bound to model that contains 2 values: id -the value i want to bind to selected index, and cities= array i want ooptions populated from. here is the 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);

I want cities to be populted after user clicked button, but the selected city must stay Moscow (because initialy the "id" was 102)

here is my 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>

My problem is that selected index got lost after cities is loaded Please help Thanks

4

1 回答 1

0

我发现我的问题出在哪里:“值”绑定是两个方向的,所以当第一次绑定到不带选项的选择时,“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)

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

于 2012-12-17T17:04:39.720 回答