1

Is there any possible fix to the below code where I face cyclic dependency using Knockout.js subscribe.

this.observable1.subscribe(function(value){
self.observable2("someValue");
});

this.observable2.subscribe(function(value){
self.observable1("someValue");
});

Where "self" is an alias to "this" and observable1 linked to combo box, and observable2 linked to date picker.

Kindly suggest

Venkat
  • 273
  • 2
  • 3
  • 13
  • 2
    Understanding why the combobox must affect the datepicker and vice versa may help in providing alternative solutions. Can you provide that reasoning? – Origineil Jun 27 '14 at 13:59
  • Are you trying to keep the two of them in synch? – TrueEddie Jun 27 '14 at 20:51
  • @TrueEddie, yes. I am trying to keep two of them in sync. – Venkat Jun 30 '14 at 11:51
  • @Origineil, When I set combo box value to "time-period", datepicker has to populate date as per the time-period value (ex., current month) and when I edit Date field which is associated with date-picker, "time-period" has to change automatically to "custom". – Venkat Jun 30 '14 at 11:56
  • You can use computed for this. Checkout this answer: https://stackoverflow.com/a/22694205 – Nandish Jul 23 '18 at 11:25

2 Answers2

1

As @Origineil said, you probably need to re-think your solution.

But if you really want to keep current solution, you could use a flag to break the cycle.

var isInnerUpdate = false;

this.observable1.subscribe(function(value){
  if (isInnerUpdate) {
    isInnerUpdate = false;
  } else {
    isInnerUpdate = true;
    self.observable2("someValue");
  }
});

this.observable2.subscribe(function(value){
    if (isInnerUpdate) {
    isInnerUpdate = false;
  } else {
    isInnerUpdate = true;
    self.observable1("someValue");
  }
});
huocp
  • 3,898
  • 1
  • 17
  • 29
0

I have used a global variable and logic as below and it worked fine for me,

var enableSubcribe = false; //global variable 
this.observable1.subscribe(function(value){ 
enableSubcribe = true; 
self.observable2("someValue");
enableSubcribe = false; 
}); 

this.observable2.subscribe(function(value){
 if(!enableSubcribe ){
self.observable1("someValue");
}
 });

Thanks to Huocp, your logic looks like works as well. Thanks all for your comments and answer.

Venkat
  • 273
  • 2
  • 3
  • 13
  • Not sure if you noticed, your enableSubscribe is not a global variable, it is a variable only visible in the function scope of your viewmodel constructor function. – huocp Jul 01 '14 at 09:04
  • sorry for that, the global variable has to be declared as this.enableSubcribe = ko.observable(); in the constructor. – Venkat Jul 07 '14 at 12:00