2
votes

How to pass the visible property of an element, in two different view model.Suppose in 1 view model i have visible is false, in another view model in click function i want to make that visible true. Can It be possible Using 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
take a look at the answers on here: stackoverflow.com/questions/9293761/… - Tanner
I would suggest adding some code to illustrate what you are trying to do otherwise you risk having your question closed. stackoverflow.com/questions/how-to-ask - Tanner
Thanks Tanner, In the reference link solution is not suitable for me.Is there any other solution for this? Thanks for the suggestion, i will update my question with some code. - Samir
in ViewModel2 you're calling this.ViewModel1, but surely that is attempting to call a variable called ViewModel1 IN viewmodel2? - Alexander Troup
Sorry @Alexander Troup, I just edit that one.Still I am not getting the output. - Samir

2 Answers

1
votes

You should try an excellent knockout-postbox. It is designed to facilitate decoupled communication between separate view models.

In your case you can use it like:

Note: syncWith used for bidirectional communication, if you want unidirectional communication then you should try subscribeTo with publishOn methods.

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);
               };
             };
0
votes
// Click Function
this.showItem= function(){
    ViewModel1.dataItem(true);
};