问题
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.
回答1:
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.
回答2:
An easy solution (but not very clean one) would be to store the indexViewModel in a global variable.
Index.cshtml:
var IndexViewModel = function () {
var self = this;
self.breadcrumbs = ko.observableArray();
};
// we create a global variable here
window.indexViewModel = new IndexViewModel();
ko.applyBindings(window.indexViewModel);
And then you can access this indexViewModel from your partial view model:
var PartialViewModel = function () {
var self = this;
self.someFunction = function(){
// Access Breadcrumbs here
// better use some wrapping functions
// instead of accessing the array directly
window.indexViewModel.breadcrumbs.push({});
};
};
ko.applyBindings(new PartialViewModel(), "someId");
</script>
来源:https://stackoverflow.com/questions/14606313/multiple-knockout-bindings-and-sharing-them