1
votes

I have an observable CommitteeTypes which holds an array of objects:

self.CommitteeTypes = ko.observableArray();

self.init = function() {
    self.CommitteeTypes([
        {
            Meeting: {descr: 'Committee', meeting_type_id: 'C' },
            Ranks: [{}, {}, ...],
            Roles: [{}, {}, ...]
        }
    ]);
}

And then I have a Select dropdown:

<select data-bind="options: $root.CommitteeTypes, optionsText: function(item) { return item.Meeting.descr; }, optionsValue: Meeting.comm_meeting_type, optionsCaption: 'Select...'"></select>

The OptionsText binding works and returns "Committee" as expected, but the OptionsValue binding does not work, it throws an error: "Reference Error: Meeting is not defined", and if I wrap it in quotes it just leaves the value empty.

The object passed in is what I expect, as I'm able to access it via the lambda, but without that this doesn't work. Did I miss something? I have almost this exact same binding working on another page (minus the lambdas). But I can't seem to figure out what I've done wrong here.

1

1 Answers

2
votes

If you use "Meeting.meeting_type_id" with the quotes in the optionsValue binding, it will look for that exact property: committeeObject["Meeting.meeting_type_id"] and not the nested value because knockout doesn't know.

So, you can use a function similar to optionsText binding to defer the accessing of the property

function viewModel() {
  const self = this;

  self.CommitteeTypes = ko.observableArray([{
      Meeting: {
        descr: 'Committee',
        meeting_type_id: 'C'
      }
    },
    {
      Meeting: {
        descr: 'Committee 2',
        meeting_type_id: 'D'
      }
    }
  ]);

  self.selectedValue = ko.observable()
  self.selectedValue.subscribe(console.log)
}

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

<select data-bind="options: CommitteeTypes, 
                   optionsText: i => i.Meeting.descr, 
                   optionsValue: i => i.Meeting.meeting_type_id, 
                   value: selectedValue, 
                   optionsCaption: 'Select...'">
</select>