Reputation: 757
I have a function in my viewmodel that loops through an array and look for items having similar ids (I know it's wrong since ids are unique, will change it to some custom data attribute when I solve this issue) and checked them if found. Here is the function:
/*
Search for similar terms in taxonomy,
if found check/uncheck them
*/
self.srcSimilar = function(tid,val){
_.filter(self.topics(), function(topic) {
return _.any(topic.children, function(member) {
tid === member.tid ? member.isSelected(val) : '';
return _.any(member.children, function(child) {
tid === child.tid ? child.isSelected(val) : '';
});
});
});
}
Since now, the function has been called inside the .subscribe method of child.is Selected observable, like this:
child.isSelected.subscribe(function(val){
self.srcSimilar(child.tid,val);
});
Now I need to transform the child.isSelected observable in a computed observable, since the checked/unchecked status depends on the child being inserted in a selectedItems observable array. So I changed the child.isSelected observable to:
child.isSelected = ko.computed({
read: function(){
},
write: function(val){
self.srcSimilar(child.tid,val);
}
});
...but this ends up in a "too much recursion" error in the console. I am missing something here, don't understand why the .subscribe works and the ko.computed write method gets stucked in a recursion. Thanks for your help.
Upvotes: 0
Views: 762
Reputation: 76
The function passed to subscribe is only called when child.isSelected CHANGES. Which means if self.srcSimilar sets isSelected on the same child which is calling self.srcSimilar the change event will not be triggered again as the value is already set and the method will not recurse.
With the computed however, the method defined for write will be called EVERY time child.isSelected is set.
Imagine a data set where A is similar to B.
With Computed
With Subscribe
Upvotes: 2