I have this recursive function that is suppose to go through a JSON object to find all the subgroups. Here is what I have:
var subgroupIds = [];
this.getSubGroups = function (groupId) {
this.getGroups("groupId="+groupId, function(groups) {
if ($.isEmptyObject(groups)) {
return subgroupIds;
} else {
$.each(groups, function(index,group) {
subgroupIds.push(group.id);
this.getSubGroups(group.id);
});
}
});
}
...where getGroups is an asynchronous function that returns all the groups.
My problem is when it gets to the recursive call, I get the error that says:
Uncaught TypeError: Object #<Object> has no method 'getSubGroups'
I'm guessing it's a scope issue but I can't figure out what's wrong with it. Any ideas?
EDIT:
As Bergi pointed out, I need to have a callback. This is what I have now:
var subgroupIds = [];
var that = this;
this.getSubGroups = function (groupId,callback) {
this.getGroups("groupId="+groupId, function(groups) {
if ($.isEmptyObject(groups)) {
return;
} else {
$.each(groups, function(index,group) {
subgroupIds.push(group.id);
callback(group.id);
that.getSubGroups(group.id);
});
}
});
}
The trouble now is when I call the callback, it says the function is undefined.
Ultimately, I want to return an array of sub group.id's. I'm not sure how to get there...