Last active
December 11, 2018 06:30
-
-
Save r4hulp/086be17cd95091df303747f663fb884d to your computer and use it in GitHub Desktop.
Communication between multiple viewmodels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
this.messageForVM2.subscribe(function(newValue) { | |
shouter.notifySubscribers(newValue, "messageToPublish"); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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