0

I am building models using Knockout. I have one parent model and couple of children. Each children has obsevrable (computed in working codem but it does not changes situation) isLoading which return true when any internal operation inside model processed.

Parent model has also computed isLoading which has subscriber. In this subscriber I want execute some code only once (I have special flag, it is ok). My problem is that this code changes somehow isLoading state of one child. And there I found that it does not raises parent computed changed.

How to bread this circular dependency?

Sample fiddle: http://jsfiddle.net/202x4755/

UPD: Key point is to use setTimeout

Alex G.P.
  • 9,609
  • 6
  • 46
  • 81

2 Answers2

1

You can make the circular update asynchronous. Because you have notify always, you should ensure that the update is necessary before kicking it off, or else you'll go into a perpetual update loop.

For this example, your subscribe should really be (only) on submodels()[1], but we'll assume you have other things going on that require it to be on the parent model.

function onStateChanged(value) {
    console.log('onStateChanged ' + value);
    // If second model finished loading automatically mark last model as loaded also
    if (!self.submodels()[1].isLoading() && self.submodels()[2].isLoading()) {
        setTimeout(function () {
            console.debug("Forcing submodel isloading to false");
            self.submodels()[2].isLoading(false);
        }, 0);
    }
}
Roy J
  • 42,522
  • 10
  • 78
  • 102
0

You should subscribe your onStateChanged function to each submodel's isLoading observable instead of the parent's isLoading observable.

self.submodels().forEach(function (submodel) {
    submodel.isLoading.subscribe(onStateChanged);
});

http://jsfiddle.net/Crimson/202x4755/1/

CrimsonChris
  • 4,651
  • 2
  • 19
  • 30
  • Not sure why this approach better then mine? Submodels could be added dynamically and potentially parent model could has a lot of submodels (20-30). – Alex G.P. Jul 17 '15 at 11:12
  • The submodel could do the subscribing when created if onStateChanged was passed to it, thus solving your dynamic concern. I believe this approach is clear in it's intent as it doesn't require any workarounds. – CrimsonChris Jul 17 '15 at 12:44