So, I understand that this is the following.
- You have a set of "options." Each parameter has some properties and Id
- You have a set of "elements", where each element has one property containing an object that is equal to one of the objects inside the options. Therefore, each βitemβ has a selected βoptionβ.
Unlike C # and other high-level environments, javascript does not have a built-in concept of equality. When you do something like objA == objB , it will check the reference equality (not true for primitive types such as numbers and strings), i.e. That two variables actually refer to the same object. For example, in .NET a class can implement IEquatable<T> (and operator overloading), so objA == objB leads to some user comparison that will determine if two different objects can be considered equal.
Therefore, when you work with a knockout and drop out, and therefore it is important to remember that to match the knockout you need to make sure that the objects being compared are really the same.
In your case, I changed your model a bit. I suggested that the property of the item selection option is called SelectedOption.
function model(options, items) { self = this; self.options = options; self.items = ko.mapping.fromJS(items);
Since you are using ko.mapping, I assume that the parameters and parameters of the elements are provided as simple javascript objects in some way (Ajax, inline js).
opts = [ { Id: 1, Name: "Option 1" }, { Id: 2, Name: "Option 2" }, { Id: 3, Name: "Option 3" } ]; var items = [ { Id: 1, Name: "Item 1", SelectedOption: { Id: 1, Name: "Option 1" } }, { Id: 2, Name: "Item 2", SelectedOption: { Id: 2, Name: "Option 2" } }, { Id: 3, Name: "Item 3", SelectedOption: { Id: 3, Name: "Option 3" } } ]; var viewModel = new model(opts, items);
Since the parameters contained in the SelectedOption parameter for each element are exactly the same as those in the properties of the options properties can now compare them for equality, and you can use them in your bindings as such:
<div data-bind="foreach: items"> <select data-bind="options: $parent.options, optionsText: 'Name', value: SelectedOption"></select> </div>
Check it out at jsfiddle: http://jsfiddle.net/niik/HDsKC/