温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Knockoutjs not updating UI when programmatically updating an observable
javascript knockout-3.0 knockout.js bootstrap-multiselect

javascript - 以编程方式更新可观察对象时,Knockoutjs不更新UI

发布于 2020-05-08 11:31:34

当我以编程方式更新可观察对象并打开模态时,为什么下拉列表没有更新?这是所有代码 https://jsfiddle.net/krob636/jes9bvLw/119/

如果尝试先更改元素的值,则更改可观察值将更新下拉列表。单击启动模式按钮,然后单击可观察按钮。所选ID会更改,但下拉列表不会更改。现在单击“元素”按钮,然后再次单击“可观察”按钮。下拉列表确实发生了变化。

Java脚本

this.selectedSimulators = ko.observableArray().extend({notify: 'always'});

this.simulators = ko.observableArray([
  new Simulator(1, 1, 1, "CH-53E", "APT", "APT 2F190-2"),
  new Simulator(2, 1, 1, "CH-53E", "EAET", "EAET 2H164-2"),
  new Simulator(3, 1, 1, "CH-53E", "WST", "WST 2F174-2")
]);

this.openModal = function() {
  $('#exampleModal').modal('show');
  this.selectedSimulators(1);

  // UI does not update without calling this 
 //$("#ddSims").val(1);
}

的HTML

  <select class="form-control" id="ddSims" multiple="multiple" data-bind="options: simulators,
      optionsText: 'typeAndSerialNumber',
      optionsValue: 'id',
      selectedOptions: selectedSimulators,
      multiselect: {includeSelectAllOption: true}">
 </select>

 <button type="button" class="btn btn-primary" data-bind="event: {click: openModal}">
    Launch modal
  </button>

查看更多

提问者
KRob
被浏览
23
Jason Spake 2020-02-20 05:57

您正在混合observables和observableArrays。selectedSimulators是一个数组,但是您将其设置为值1,而不是将值1推入数组。试试吧self.selectedSimulators.push(1);