Below I am using backbone js to fetch a collection. On the request's response, I would like to perform some logic on the collection to massage the data. I am modifying the parse method on the parent collection (source types) to attach a child collection (source accounts) and only include a source type if there are actually source accounts.
I don't want to render this without having all the data loaded primarily, so I figure with javascript the only way to be safe is with a success callback.
As you can see in the below code, inside the parse function, I construct a new object called "response_object". The issue is that when i attempt to pack this object inside the success callback, the collection does not include any of the object that i packed into it. How would you rewrite this to make this work correctly?
window.AdminSourceTypes = Backbone.Collection.extend({
model: window.AdminSourceType,
url: '/api/sources',
parse: function(response){
// create response object
response_object = [];
x = 0;
_.each(response, function(item){
//get child collection (accounts) from one of "source type's" attributes
collection = new window.AdminAccounts();
collection.url = item.accounts_url;
//get all accounts
collection.fetch({
//only add the source type to the response object
//if there are accounts associated to it
success: function(accounts_collection){
if(accounts_collection.size() > 0){
response_object[x] = item;
}
}
});
x++;
});
return response_object;
}
});