Search code examples
knockout.jsknockout-mapping-plugin

How to set a child view model and have it update html?


I'm new to knockout and I'm trying to set a child viewmodel after mapping some data using the mapping plugin. I thought it would be as simple as setting in my sample, or the one below but neither work. Any ideas? I've setup a sample to help

jsfiddle

viewModel.owner = ownerTwoViewModel;


viewModel.owner(ownerTwoViewModel);

Solution

  • viewmodel.owner is not an observable property that is why it is not updating. so make it observable.

    var project = {
      title: "knockout",
      owner: ko.observable({
        name: 'Steve',
        title: 'Mr.'
      })
    };
    var ownerTwo = {
      name: 'Sarah',
      title: 'Mrs.'
    };
    
    //viewmodels
    var viewModel = ko.mapping.fromJS(project);
    var ownerTwoViewModel = ko.mapping.fromJS(ownerTwo);
    
    //binding
    ko.applyBindings(viewModel);
    //jquery event
    $("#target").click(function () {
        viewModel.owner(ownerTwoViewModel);
    });
    

    Jsfiddle Demo