Warm tip: This article is reproduced from stackoverflow.com, please click
javascript knockout-3.0 knockout.js bootstrap-multiselect

Knockoutjs not updating UI when programmatically updating an observable

发布于 2020-05-05 07:36:26

Why is the dropdown not updating when I programmatically update the observable and open the modal? Here is all the code https://jsfiddle.net/krob636/jes9bvLw/119/

Changing the observable updates the dropdown if I try changing the element's value first. Click Launch modal button then click the Observable button. The selected id changes but not the dropdown. Now click the Element button, then click Observable button again. The dropdown does change.

Javascript

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>
Questioner
KRob
Viewed
24
Jason Spake 2020-02-20 05:57

You're mixing observables and observableArrays. selectedSimulators is an array, but then you're setting it to a value of 1 instead of pushing a value of 1 to the array. Try self.selectedSimulators.push(1); instead.