Reputation: 527
I have been working on a Rails app using Backbone on the frontend. It has two models, publication and article. I wrote the following function in the publications backbone router and it supposed to delete the specified publication and all it's related articles. It deletes the publication just fine but I am running into an issue when it comes to deleting the articles. Here is the code:
publications_router.js
delete_publication: function(id){
var publication = new SimpleGoogleReader.Models.Publication({id: id});
publication.fetch();
publication.destroy();
var articles = new SimpleGoogleReader.Collections.Articles();
articles.fetch({
success: function(data){
_.each(data.models, function(item){
if (item.toJSON().publication_id == id) {
console.log(item);
}
});
}
});
}
This works great for printing each item in the console. However, if I change the console.log(item) line to say:
item.destroy();
It will only destroy every other item. Obviously I would like to correct this so the function destroys all the items and not every other one.
Can anybody tell me why this is happening and what we can do to fix it?
Upvotes: 0
Views: 60
Reputation: 3669
First filter out the items you want to destroy.
var tobeDeleted = _.filter(data.models, function(item){
return (item.toJSON().publication_id == id);
});
... and then destroy
_.invoke(tobeDeleted, "destroy");
Upvotes: 1