2

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);
      };
    };
Samir
  • 1,312
  • 1
  • 10
  • 16
  • take a look at the answers on here: http://stackoverflow.com/questions/9293761/knockoutjs-multiple-viewmodels-in-a-single-view – Tanner Feb 28 '14 at 10:19
  • I would suggest adding some code to illustrate what you are trying to do otherwise you risk having your question closed. http://stackoverflow.com/questions/how-to-ask – Tanner Feb 28 '14 at 10:22
  • 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 Feb 28 '14 at 10:29
  • in ViewModel2 you're calling this.ViewModel1, but surely that is attempting to call a variable called ViewModel1 IN viewmodel2? – Alexander Troup Feb 28 '14 at 10:46
  • Sorry @Alexander Troup, I just edit that one.Still I am not getting the output. – Samir Feb 28 '14 at 11:02
  • when you update a variable, you don't create a new observable, you just update the old one, so instead of ViewModel1.dataItem = ko.observable(true), you would just do ViewModel1.dataItem(true); – Alexander Troup Feb 28 '14 at 11:04
  • It's worth going through the tutorials at http://learn.knockoutjs.com/ – Alexander Troup Feb 28 '14 at 11:06
  • I tried with your suggesation @Alexander, But it is throwing error. It will not able find the the second view model. – Samir Feb 28 '14 at 11:23

2 Answers2

1

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);
               };
             };
Gaurav
  • 8,367
  • 14
  • 55
  • 90
0
// Click Function
this.showItem= function(){
    ViewModel1.dataItem(true);
};
John Little
  • 778
  • 6
  • 14