value binding in KnockoutJs fails for select when

2019-03-25 15:16发布

问题:

I am trying to use the value binding on the select element, as described in this fiddle: http://jsfiddle.net/MikeEast/nM6dd/2/

However, I cannot seem to be able to set the selected option (value binding).

I know I can use the optionsValue binding, but that makes the value a string instead of an object which is not preferable. If that is the only way to go, how would I do to ensure that the selected option is written back to the view model?

Thanks!

回答1:

Here is the solution. You have to add the attribute optionsValue: 'id' to the data-bind. You also have to put a function in you viewModel that returns the selected object.

HTML

<select data-bind="options: items, optionsText: 'name', optionsValue: 'id', value: selectedItemId"></select>
<span data-bind="text: selectedItem().name"></span>

JS

var viewModel = function () {
   this.items = ko.observableArray([
       { id: 1, name: "Apple" }, 
       { id: 2, name: "Orange"},
       { id: 3, name: "Banana"}
   ]);
   this.selectedItemId = ko.observable(3);
   this.selectedItem = function() {
       var self = this;
       return ko.utils.arrayFirst(this.items(), function(item) {
           return self.selectedItemId() == item.id;
       });
   }.bind(this);
};

var vm = new viewModel();
ko.applyBindings(vm);

Cheers!



标签: knockout.js