使用knockout选择元素或元素类型

时间:2016-08-18 06:23:57

标签: javascript knockout.js

我有两个组合框,并且想要选择stationType或station(如果选择了station,则将setType设置为零,反之亦然)。当其中一个代码发生更改时,以下代码的结果将设置为零。有没有办法保留我的选择并仅重置另一个框?

<select class="form-control input-sm" data-bind="options: lookups.stationTypes, optionsText: 'Name', optionsValue: 'Id', value: ProductPlanItem().StationTypeId"></select>

<select class="form-control input-sm" data-bind="options: lookups.stations, optionsText: 'Name', optionsValue: 'Id', value: ProductPlanItem().StationId"></select>

ProductPlanItem是这样的:

function ProductPlanItem() {
        var me = this
        me.StationTypeId = ko.observable()
        me.StationId = ko.observable()
        me.StationTypeId.subscribe(function () {
            me.StationId(0)
        })
        me.StationId.subscribe(function () {
            me.StationTypeId(0)
        })
    }

1 个答案:

答案 0 :(得分:0)

您可以使用ko.computed readwrite功能。您当前设置的问题是在第一个订阅中设置StationId会触发第二个订阅。

以下是您在示例中的基本行为:

function ViewModel() {
  this.first = ko.observable(1);
  this.second = ko.observable(2);

  this.oddsAndZero = [0, 1, 3, 5, 7, 9];
  this.evensAndZero = [0, 2, 4, 6, 8, 10];

  this.firstSelection = ko.computed({
    read: this.first,
    write: function(newValue) {
      this.first(newValue);
      this.second(0);
    },
    owner: this
  });
  
  this.secondSelection = ko.computed({
    read: this.second,
    write: function(newValue) {
      this.second(newValue);
      this.first(0);
    },
    owner: this
  });

}

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>


<select data-bind="options: oddsAndZero, value: firstSelection"></select>
<select data-bind="options: evensAndZero, value: secondSelection"></select>