deferring dependencies when loading data using kno

2019-07-29 11:34发布

问题:

When my user logs in, I load a bunch of data from the server. This take a lot of time because it seems that the dependent observables are updated on every addition to an observableArray(). I would like to defer the evaluation of all dependencies until all data are loaded. I have seen how deferEvaluation: true can be used to affect the behavior of a specific ko.computed() variable, but I would like to isolate the observable until I know it's done being updated, and then invalidate the entire model to redraw the view.

I've created a jsfiddle to illustrate the problem. Note that in my real code, I am using the mapping plugin to load objects, but here I just simulate all the dependencies with a .subscribe function that gets called on every state change. I would like to prevent it from being called until the very end.

回答1:

Typically, in a situation like this you would access the underlying array from an observableArray and push to it. Then, you would either push the last one to the observableArray or call myObservableArray.valueHasMutated().

So, in general it would look like:

var underlyingArray = this.items();
underlyingArray.push(one);
underlyingArray.push(two);
underlyingArray.push(three);
this.items.valueHasMutated();

In your fiddle, you could do this.document().history().push(this);. Then, you would have to go back through and call valueHasMutated() on the the affected documents, if you wanted your subscription to run.



标签: knockout.js