Update entire object with value binding on select with knockout.js?

1.1k Views Asked by At

I have a select dropdown menu which shows a list of objects, with the name property being the text displayed, the id property being the value each option is bound to, and a value: user.id binding which is from a separate property on another object.

<td data-bind=""><select data-bind="options: peopleResponsible, optionsText: 'name', optionsValue: 'id', value: user.id"></select></td>

When I select a new person object from the dropdown list, only the id on the user is being updated. All of the other properties (name, username, age, etc) are not being updated.

What I need for it to do is when a new peopleResponsible option is selected, I want it to copy across all of the properties from that object to the user object.

I have a suspicion that at the moment it currently does not work because the user object itself is not observable, only its properties are. Here is how my data is being mapped:

ko.mapping.fromJS(taskOutlines, {}, mappedTaskOutlines);

Where a TaskOutline contains many Tasks, and each Task contains a single User.

Any ideas?

2

There are 2 best solutions below

2
On BEST ANSWER

You can do this:

var vm = {
  peopleResponsible: ko.observableArray([{
    id: ko.observable(1),
    name: ko.observable("p1")
  }, {
    id: ko.observable(2),
    name: ko.observable("p2")
  }, {
    id: ko.observable(3),
    name: ko.observable("p3")
  }]),
  selectedUser: ko.observable()
}

vm.selectedUser(vm.peopleResponsible()[1]); // pre select a user

ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>



<select data-bind="options: peopleResponsible, optionsText: 'name', value: selectedUser"></select>
<div data-bind="with: selectedUser">
  <p>Id:
    <label data-bind="text: id"></label>
  </p>
  <p>Name:
    <label data-bind="text: name"></label>
  </p>
</div>

When a selection is made that selection will be a reference to the arbitrary object in the observable array, properties and all. This selected object will then be placed in "selectedUser" observable.

So in short, removing the "optionsValue" binding will bind the entire object instead of the id property.

0
On

The value binding only sets one observable. Not knowing how things are used, it's hard to say what you should do to get the result you want. One possibility is to make a function that does the copying and subscribe to the user.id.