Skip to content

Instantly share code, notes, and snippets.

@r4hulp r4hulp/vm1.js
Last active Dec 11, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.