Skip to content

Instantly share code, notes, and snippets.

@r4hulp
Last active December 11, 2018 06:30
Show Gist options
  • Save r4hulp/086be17cd95091df303747f663fb884d to your computer and use it in GitHub Desktop.
Save r4hulp/086be17cd95091df303747f663fb884d to your computer and use it in GitHub Desktop.
Communication between multiple viewmodels
var self = this;
self.firstName = ko.observable();
self.lastName = ko.observable();
self.fullName = ko.computed(function(){
return self.firstName + " " + self.lastName;
});
};
var viewModel2 = function(){
var self = this;
self.premium = ko.observable();
};
ko.applyBindings(new viewModel1(), document.getElementById("container1"));
ko.applyBindings(new viewModel2(), document.getElementById("container2"));
// view model 1 definition
var viewModel1 = function(){
this.firstName = ko.observable("Wrapcode");
this.messageForVM2 = ko.observable("Hello from first view model");
this.message = ko.observable("Hello this is vm1")
};
//view model 2 definition
var viewModel2 = function(vm1){
this.firstName = ko.observable(vm1.firstName());
this.message = ko.observable(vm1.messageForVM2());
};
//master view model with instances of both the view models.
var masterVM = (function(){
this.viewModel1 = new viewModel1(),
this.firstName = "Rahul",
this.viewModel2 = new viewModel2(this.viewModel1);
})();
ko.applyBindings(masterVM)
this.messageForVM2.subscribe(function(newValue) {
shouter.notifySubscribers(newValue, "messageToPublish");
});
shouter.subscribe(function(newValue) {
this.message(newValue);
}, this, "messageToPublish");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment