Asp.net mvc 3 多个敲除绑定并共享它们

Asp.net mvc 3 多个敲除绑定并共享它们,asp.net-mvc-3,knockout.js,sammy.js,Asp.net Mvc 3,Knockout.js,Sammy.js,所以我有一个场景,在我的主页上有敲除绑定 Index.cshtml: <div data-bind="foreach breadcrumbs"> <div> <script> var IndexViewModel = function () { var self = this; self.breadcrumbs = ko.observableArray(); }; ko.applyBindings(IndexViewModel); &l

所以我有一个场景,在我的主页上有敲除绑定

Index.cshtml:

<div data-bind="foreach breadcrumbs">
<div>

<script>
 var IndexViewModel = function () {
    var self = this;
    self.breadcrumbs = ko.observableArray();
 };
 ko.applyBindings(IndexViewModel);
</script>
 var IndexViewModel = function () {
    var self = this;
    self.breadcrumbs = ko.observableArray();
 };
 // we create a global variable here
 window.indexViewModel = new IndexViewModel();

 ko.applyBindings(window.indexViewModel);

var IndexViewModel=函数(){
var self=这个;
self.breadcrumbs=ko.observearray();
};
ko.应用绑定(IndexViewModel);
以及加载在Index.cshtml中的部分视图。局部视图有自己的淘汰绑定:

<div id="someId">

</div>
<script>
  var PartialViewModel = function () {
        var self = this;
        self.someFunction = function(){
            // Access Breadcrumbs here
        };
  };
  ko.applyBindings(PartialViewModel, "someId");
</script>

var PartialViewModel=函数(){
var self=这个;
self.someFunction=function(){
//在这里访问面包屑
};
};
应用绑定(PartialViewModel,“someId”);

我想从第二个局部视图访问面包屑阵列,并向其中添加项目。我甚至不确定这是否可能。请帮忙。我也在使用sammy.js,但出于这个目的,它没有那么重要。

我不喜欢视图模型之间有依赖关系,所以我以前使用了jQuery pubsub插件来允许视图模型以解耦的方式相互对话。你可以在中看到一个例子

基本上,当您更新面包屑时,使用新数组调用publish,另一个视图模型将订阅该事件。

一个简单的解决方案(但不是很干净的解决方案)是将indexViewModel存储在全局变量中

Index.cshtml:

<div data-bind="foreach breadcrumbs">
<div>

<script>
 var IndexViewModel = function () {
    var self = this;
    self.breadcrumbs = ko.observableArray();
 };
 ko.applyBindings(IndexViewModel);
</script>
 var IndexViewModel = function () {
    var self = this;
    self.breadcrumbs = ko.observableArray();
 };
 // we create a global variable here
 window.indexViewModel = new IndexViewModel();

 ko.applyBindings(window.indexViewModel);
然后可以从局部视图模型访问此indexViewModel:

  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>
var PartialViewModel=函数(){
var self=这个;
self.someFunction=function(){
//在这里访问面包屑
//最好使用一些包装功能
//而不是直接访问阵列
window.indexViewModel.breadcrumbs.push({});
};
};
应用绑定(新PartialViewModel(),“someId”);

您的脚本将无法工作。您需要使用new调用ViewModel构造函数。如果您正在VM之间的KO中执行pubsub,那么您可能需要查看我在此处创建的邮箱插件:。它有一些可观察的扩展,可以很容易地通过中介自动发布/订阅可观察的更改。我最初做这项工作时确实看过,但对于那个项目,我需要在每个活动中做更多的工作,因此我选择了pubsub。您的插件非常适合此场景,您是正确的。:)敲除邮箱是否与敲除2.2.0兼容?我已经在我的源代码中包含了这个库,但是一直没有得到任何提示:无法调用undefined@RPNiemeyerPostbox的“subscribe”方法与2.2兼容。听起来你可能还有别的事。如果你有机会,请随时给我发送电子邮件ryan at Knockout Meout。net@RPNiemeyer我想出来了。佩巴克。谢谢