문제

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?

도움이 되었습니까?

해결책 3

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.

다른 팁

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();}});
});

I have no experience with backbone, but I would approach this problem like so:

  • Get the number of active_transactions.
  • On transaction.save(), check the number of processed transactions (in the success and/or error callback), if it matches the number of active_transactions, then destroy the model.

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();}});
            }
          }
        });
    }
  );

}

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top