Search code examples
knockout.jsknockout-subscribe

Cyclic dependency using Knockout subscribe


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


Solution

  • 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");
      }
    });