Wednesday, August 22, 2012

recursion – Recursive JavaScript returning after first pass

I have the following recursive javascript function which is looping over the children of a backbone.marionette CollectionView that has children ItemViews that are in turn CollectionViews:



findViewByCid: function(cid, children){
var col = (arguments.length === 1) ? this.children : children;

if(cid in col){
return col[cid];
}

for(child in col){
var grandChildren = col[child].children;

if(cid in grandChildren){
return grandChildren[cid];
}

if(grandChildren && (!jQuery.isEmptyObject(grandChildren))){
return this.findViewByCid(cid, grandChildren);
}
}
}


I am calling it like this:


var view = DocumentManager.Documents.treeRoot.findViewByCid(model.cid);


The problem is the line:



return this.findViewByCid(cid, grandChildren);


If I have a hierarchy like this



c1
|_c2
|_c3
|_c4
|_c5


Then te return statement will cause the function to exit after passing th3 c2 node and never get to c4 etc.


If I remove the return statement, the correct child is found but null is returned.


How can I continue parsing the hierarchy and return a value?






Rating: 2 out of 5 based on 5 ratings



The post recursion – Recursive JavaScript returning after first pass appeared first on Javascript ASK.






via Javascript ASK http://javascriptask.phpfogapp.com/recursion-recursive-javascript-returning-after-first-pass.html

No comments:

Post a Comment