使Knockout.JS订阅全球可用

时间:2017-01-18 13:34:25

标签: asp.net knockout.js

我有一个ASP.NET应用程序,我在我的应用程序中使用Knockout JS来完成一些最小的任务。但是我有一些正在计算要显示的值的EditorTemplates。我想从其他一些EditorTemplates访问这些值。我想我可能会使用Knockout的原生pub / sub功能,这意味着我会在一个EditorTemplate中写入通知代码,如下所示:

new ko.subscribable().notifySubscribers(this.calculatedValue, "customTopic");

然后在我的其他EditorTemplate

中更改时接收此值
new ko.subscribable().subscribe(function (newValue) {
        alert(newValue);            
    }, this, "customTopic");

当然,这段代码不起作用,因为我每次都在创建一个new ko.subscribable()

如何在我的所有视图中创建一个ko.subscribable

1 个答案:

答案 0 :(得分:1)

  • 首先,您需要全局定义subscribable变量的新实例。
  • 将其他子视图模型subscribe置于您定义的可订阅变量中。
  • 每当发生任何更新时,都会使用notifySubscribers通知任何订阅者。

示例:https://jsfiddle.net/kyr6w2x3/149/

查看:

 <div id="one">
    <h1>MainVM:</h1>
    <input type="text" data-bind="textInput:Name">
    <hr>
  </div>

  //-------------------------------------------------
  <div id="two">
    <h1>SecondVM:</h1>
    <div data-bind="text:NameSecondVM"> </div>
  </div>

<强>型号:

 var shouterValueOfName = new ko.subscribable();

<script type="text/javascript">
  var MainViewModel = function(){
    var self = this;
     self.Name = ko.observable();
     self.Name.subscribe(function (newValue) {
        newValue = newValue ? newValue + " Sent from MainVM" : "" ;
        shouterValueOfName.notifySubscribers(newValue, "secondVMTakeThis");
    }, self);
  }        
</script>

<script type="text/javascript">
  var SecondViewModel = function(){
     var self = this;
     self.SecondVM = ko.observable();
     self.NameSecondVM = ko.observable();
     shouterValueOfName.subscribe(function (newValue) {
       self.NameSecondVM(newValue);
     }, this, "secondVMTakeThis");
  }
</script>
var viewModelA = new MainViewModel();
var viewModelB = new SecondViewModel();
ko.applyBindings(viewModelA, document.getElementById("one"));
ko.applyBindings(viewModelB, document.getElementById("two"));