简体   繁体   中英

Knockout mapping for nested Complex Objects

I have a viewmodel with child objects. How do I define the mapping for properties of the child objects?

public class ViewModel
{
    public ManageComparatorSelectionsViewModel ManageComparatorSelectionsViewModel { get; set; }
    public ManageComparatorItemViewModel CurrentComparatorItem { get; set; }
}


public class ManageComparatorSelectionsViewModel
{
    public IList<Edition> Editions { get; set; }
    public IList<Year> Years { get; set; }
}

public class ManageComparatorItemViewModel
{
    public Edition ChosenEdition { get; set; }
    public Year ChosenYear { get; set; }
}

I am doing the following to initialize knockout

    var mapping = {
        'ManageComparatorSelectionsViewModel.Editions': {
            key: function (data) {
                return ko.utils.unwrapObservable(data.Id);
            }
        },
        'ManageComparatorSelectionsViewModel.Years': {
            key: function (data) {
                return ko.utils.unwrapObservable(data.Id);
            }
        }
    };
    var viewModel = ko.mapping.fromJS(viewModelData, mapping);

    ko.applyBindings(viewModel);

is there any reason you need those to be unwrapped? you could always get at those same objects by getting the property() or by doing ko.toJS() item you are looking at.

EDIT:

For the dropdown:

<select data-bind=" template : { 'name' : 'templateID', foreach : optionlist } "></select>

With a template that looks like this:

<script type="html/text" id="templateID">
      <option value="${ key }">${ text }</option>
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM