I’m trying to split my view models into multiple reuseable view models.
I have one view model which contains several dropdowns and one button.
var TopView = function () {
self.DropDownA = ko.observableArray();
self.selectedDDA = ko.observable();
self.DropDownB = ko.observableArray();
self.selectedDDB = ko.observable();
$.getJSON("someAPIurl", function (result) {
ko.mapping.fromJS(result, {}, self);
}); //this builds dropdownA
$self.selectedDDA.subscribe(function(newValue) {
$.getJSON("anotherAPI"+newValue, function (result) {
ko.mapping.fromJS(result, {}, self);
});
}; // this builds dropdownB
$self.buttonClicked = function() {
alert("I clicked!");
}
}
My main viewmodel looks like this:
var MainView = function () {
var self = this;
var topView = ko.observable({ TopView: new TopView() });
// How do i get the selected values from topView once the user clicks the button???
}
How do I subscribe to DropDownA and DropDownB selected values from my mainview???
Please help! Thank you!
You do not need to make the
TopViewitself observable as long as you don’t want to exchange it completeley. You just can create it as a property ofMainViewand access it simply like that in your bindings:TopView stays as it is (after you fixed your using of
selfand$selfwithout defining them)MainView would look like that:
JSFiddle example