Computed observable calling itself in an infinite loop

716 views
Skip to first unread message

ego...@gmail.com

unread,
Mar 7, 2012, 6:47:35 AM3/7/12
to KnockoutJS
Hello again,

I'm having problems with computed again. My problem now is that I have
to modify an observable inside my computed just to create some other
objects.

Here it is my scenario:

1. I have a computed that will expose an array of objects with
observable properties.

2. This computed is also depending on some observables that will
influence the way the resulting array's objects are built, meaning
that depending on them the objects with observable properties returned
into the final resultant array will have to be created and modified
inside the computed.

3. This makes the computed to subscribe to the created object (with
observable properties) so when it modifies some of its properties
forces a reevaluation of the computed entering in an infinite loop of
recursion.

I solved this making a safeCompute, just a wrapper around the computed
that uses a flag to stop recursion. And it works great!! But not with
the v2.1.0pre version.

I guess that's maybe something related to dependency management
optimizations into the last build.

here you can see my safeComputed function:

safeComputed: function (f, ctx) {

var flag = false;
if (!ctx) {
ctx = this;
}

return ko.computed(function () {
if (flag) {
return false;
} else {
flag = true;
}

var returnValue = f();

flag = false;

return returnValue;

}, ctx);

}

With v2.1.0.pre and using the safeComputed I'm getting an error:

_subscriptionsToDependencies.splice(i, 1)[0] is undefined

ln.1172


Obviously, if I don't use my safeComputed then I have the recursion
problem again.

Any ideas on this matter?

Thank you very much!!

--
Roberto

Roberto Huertas Muyo

unread,
Mar 7, 2012, 7:55:54 AM3/7/12
to knock...@googlegroups.com
Hello,

I solved the issue by changing the logic. I don't use a computed with all that "building array of new objects with observables"  stuff anymore. Instead, I use a normal observable that will hold the final array. Then create a function with the  "building array of new objects with observables"  logic and finally I subscribe to all dependent observables manually to then call the creation function which will then fill the normal observable with the array of objects with observable properties.

This way it works ok. A pity we have to manually subscribe to dependent observables and then launch the logic in a separate method and then  fill an observable. It would be nice if the computed observable could manage all this avoiding recursion. I'm still thinking about my version of safeComputed here. Maybe with some refactor it  will work with latest ko version.

Thanks!

--
Roberto.

Michael Best

unread,
Mar 7, 2012, 6:05:23 PM3/7/12
to KnockoutJS
Here is an issue I opened to discuss solutions to this problem:
https://github.com/SteveSanderson/knockout/issues/326
Reply all
Reply to author
Forward
0 new messages