Reputation: 3257
I've got this code currently:
handleSubmit: function(e)
{
var to_bucket = this.$('.transaction_bucket').val();
// Move all the transactions for this bucket to the selected bucket
window.app.model.active_transactions.each(
function(transaction)
{
transaction.set({bucket_id: to_bucket});
transaction.save();
}
);
this.model.destroy({success: function() { window.app.model.buckets.fetch();}});
}
How can I modify this so that the destroy only triggers once all the _.each ajax transactions happen? If I had one previous ajax request, I would just use the success: parameter, but I can't do that here.
What's the right way to do this in backbone?
Upvotes: 2
Views: 365
Reputation: 33344
model.save return the xhr object used in the request. With jQuery 1.5, these objects are deferred objects you can use to build a synchronization mechanism.
For example,
var to_bucket = this.$('.transaction_bucket').val(),
calls=[],
mdestroy=this.model.destroy;
window.app.model.active_transactions.each(function (transaction) {
transaction.set({bucket_id: to_bucket});
calls.push(transaction.save());
});
$.when.apply($, calls).then(function () {
mdestroy({success: function () {window.app.model.buckets.fetch();}});
});
Upvotes: 1
Reputation: 1194
Just keep track of the number of transactions already processed and trigger the destroy in the last callback like so:
handleSubmit: function(e)
{
var to_bucket = this.$('.transaction_bucket').val();
var remainingTransactions = window.app.model.active_transactions.length;
var self = this;
window.app.model.active_transactions.each(
function(transaction)
{
transaction.save({bucket_id: to_bucket}, {
success: function(){
remainingTransactions -= 1;
if(remainingTransactions < 1) {
self.model.destroy({success: function() { window.app.model.buckets.fetch();}});
}
}
});
}
);
}
Upvotes: 0
Reputation: 3257
One possible solution would be to create a custom API method that took the transactions as parameters and did the job on the server side. This would reduce https requests and increase performance as well.
Upvotes: 0
Reputation: 9650
I have no experience with backbone, but I would approach this problem like so:
Upvotes: 0