So I have a scenario where I am have knockout binding on my main page.
Index.cshtml:
<div data-bind="foreach breadcrumbs">
<div>
<script>
var IndexViewModel = function () {
var self = this;
self.breadcrumbs = ko.observableArray();
};
ko.applyBindings(IndexViewModel);
</script>
And a Partial View that loads inside the Index.cshtml. The partial view has its own knockout bindings:
<div id="someId">
</div>
<script>
var PartialViewModel = function () {
var self = this;
self.someFunction = function(){
// Access Breadcrumbs here
};
};
ko.applyBindings(PartialViewModel, "someId");
</script>
I want to access the breadcrumbs observableArray from the second partial view and add items to them. I am not even sure if this possible. Please help. I am also using sammy.js but for this purpose its not that relevant.
An easy solution (but not very clean one) would be to store the indexViewModel in a global variable.
Index.cshtml:
And then you can access this indexViewModel from your partial view model:
I don't like having to have dependencies between view models, so I've previously used a jQuery pubsub plugin to allow view models to talk to each other in a decoupled manner. You can see an example of it in this answer
Basically, when you update the breadcrumb, call publish with the new array, and the other view model would subscribe to that event.