I have a complex knockout viewmodel that has been created using the mapping plugin. I also update the viewmodel using the mapping plugin:
ko.mapping.fromJS(json, viewmodel);
I have a couple of subscriptions that use more than one viewmodel field to calculate a result. The mapping plugin updates each field separately and knockout executes the subscriptions on every change. Because not all values are updated on the same time the calculations sometimes work with a mix of old and new values for different field, which causes issues in my case.
Is there are way to tell the mapping plugin or knockout in general to wait with the evaluation of dependencies until I tell it that all values have been set?
What I ended up doing was creating a observable in my viewmodel that was given a value after the batch update finished. I also defined a manual subscription that executes the relevant code at that moment:
viewmodel.finishedBatchUpdate : ko.observable();
...
ko.mapping.fromJS(json, viewmodel);
viewmodel.finishedBatchUpdate.notifySubscribers(true);
...
viewModel.finishedBatchUpdate.subscribe(function() {
// my code
});
I could have also created a pureComputed
and have that depend on this observable, but I do not need to bind anything on this pureComputed itself. Having a manual subscription is cleaner in my view.