I have created a View Model object for use with KnockoutJS.
It has a property called ‘Years’ which is an observable array…
viewModel.Years = ko.observableArray([]);
I then have a computed observable, in which I want to update the contents of the array…
viewModel.FuturePrediction = ko.computed(function () {
viewModel.Years.removeAll();
// etc...
});
The problem I’m having is that this appears to create an infinite loop. I’m guessing that Knockout is detecting that I’m accessing the ‘Years’ property and creating a dependency between it and the ‘FuturePrediction’ property.
As soon as I attempt to modify the contents of the array, the computed function gets triggered again. The problem is that all I’m doing is updating the ‘Years’ array, not reading it – and therefore there isn’t actually a dependency.
Any ideas what I can do to resolve this?
In KO 2.1, computed observables cannot trigger themselves, so you would be in better shape with 2.1.
Calling the array manipulation methods do read and set the array, so it would create a dependency. You could do
viewModel.Years([]);as long as you are not depending on the original underlying array for anything (have references to it elsewhere).I am not sure about your full scenario, but an option would be to build up your “new” array and then finally set the result as the value of
Yearsrather than clearing it first.Like:
Again, I am not sure about your exact scenario, but if the end goal is to create a new array based on some criteria, then you could have
FuturePredictionbe the array and return it as the result of the computed observable. Just not sure about your situation exactly.