multiple knockout bindings and sharing them

2019-07-27 13:46发布

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.

2条回答
我想做一个坏孩纸
2楼-- · 2019-07-27 14:33

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>
查看更多
别忘想泡老子
3楼-- · 2019-07-27 14:34

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.

查看更多
登录 后发表回答