Knockout在两个视图模型之间传递值

时间:2014-02-28 09:59:57

标签: knockout.js

如何在两个不同的视图模型中传递元素的visible属性。在1个视图模型中假设我可见为false,在单击函数中的另一个视图模型中我想使其可见为真。可以使用Knockout。

   ViewModel1 = function() {
        var self = this;
        this.dataItem = ko.observable(false);
      };

Viewmodel 2

   ViewModel2 = function() {
      var self = this;

      // Click Function
      this.showItem= function(){
          ViewModel1.dataItem = ko.observable(true);
      };
    };

2 个答案:

答案 0 :(得分:1)

你应该尝试一个优秀的knockout-postbox。它旨在促进不同视图模型之间的分离通信。

在您的情况下,您可以使用它:

注意: syncWith 用于双向通信,如果您需要单向通信,那么您应该使用 publishOn subscribeTo >方法。

Viewmodel 1

ViewModel1 = function() {
               var self = this;
               this.dataItem = ko.observable(false).syncWith("visible", true); 
             };

Viewmodel 2

ViewModel2 = function() {
               var self = this;

               self.dataItem = ko.observable().syncWith("visible", true); 

               // Click Function
               this.showItem= function(){
                    self.dataItem = ko.observable(true);
               };
             };

答案 1 :(得分:0)

// Click Function
this.showItem= function(){
    ViewModel1.dataItem(true);
};