James
James

Reputation: 311

How to update view model data from another view model in Knockout

I am using Knock out to bind different sections in a page. I have two view model data for each section. While changing a element in one view model based on that want to change another element in another view Model.Each view model data have ID field to identify each data.

Upvotes: 0

Views: 797

Answers (1)

Kevin Smith
Kevin Smith

Reputation: 14436

You can just pass one of the view model in to the other view model:

var ViewModel1 = function() {
    var self = this;
    self.selectedItem = ko.observable();
};

var ViewModel2 = function(viewModel) {
    self = this;
    self.content = ko.observable();
    viewModel.selectedItem.subscribe(function(){
       self.content('value changed')
    });
};


var viewModel1 = new ViewModel1();
var viewModel2 = new ViewModel2(viewModel1);

ko.applyBindings(viewModel1, document.getElementById("part1"));
ko.applyBindings(viewModel2, document.getElementById("part2"));

Upvotes: 2

Related Questions