knockout.jsdrop-down-menuundefinedcomputed-observable

How assign undefined value in a knockout JS variable?


I have 2 dropdownlists and one list of result with a binding using computed observable function something like this:

     self.Records = ko.computed(function() {
                    if (self.dropdown1 !== undefined) {
 ...
                        return Collection[0];
                    }

                    if (self.dropdown2() != undefined) {
                     ...
                        return Collection[0];
                    }
                });

But my problem is that I need to set in undefined the value on self.dropdown1 when I change the valie of the dropdownlist2, for my Collection of records can change.

I'm changing the value of the first dropdown with jquery like this:

  $('#reportTypeSelection').prop('selectedIndex', 0);

But the binding is not refreshing. Any advices please.


Solution

  • I think you should not be using jQuery to code that logic. Here is an example of how this can be done in a view model with view not knowing anything about the logic.

    var VM = function() {
      
      var self = this;
    
      self.items = ko.observableArray(["Item1", "Item2", "Item3"]);
    
      self.dropdown1 = ko.observable();
      self.dropdown2 = ko.observable();
    
      self.dropdown1.subscribe(function(newValue) {
        if (newValue) {
          self.dropdown2(null);
        }
      });
    
      self.dropdown2.subscribe(function(newValue) {
        if (newValue) {
          self.dropdown1(null);
        }
      });
    }
    
    ko.applyBindings(new VM());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
    
    <select data-bind="options:items, optionsCaption:'Select first item',value: dropdown1"></select>
    
    <select data-bind="options:items, optionsCaption:'Select second item',value: dropdown2"></select>