Domanda

Ho questo codice attualmente:

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

Come posso modificare questo in modo che il solo distruggere innesca una volta tutto l'ajax _.each transazioni avvengono? Se avessi avuto una precedente richiesta AJAX, vorrei solo usare il successo:. Parametro, ma non posso farlo qui

Qual è il modo giusto per fare questo in spina dorsale?

È stato utile?

Soluzione 3

Una possibile soluzione potrebbe essere quella di creare un metodo API personalizzata che ha preso le transazioni come parametri e ha fatto il lavoro sul lato server. Ciò ridurrebbe le richieste HTTPS e aumento delle prestazioni pure.

Altri suggerimenti

model.save restituire l'oggetto XHR utilizzata nella richiesta. Con jQuery 1.5, questi oggetti sono differita oggetti href="http://api.jquery.com/category/deferred-object/" è possibile utilizzare per costruire un meccanismo di sincronizzazione.

Ad esempio,

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

Non ho esperienza con la spina dorsale, ma vorrei affrontare questo problema in questo modo:

  • ottenere il numero di active_transactions.
  • On transaction.save (), controllare il numero di transazioni elaborate (per il successo e / o callback errore), se corrisponde al numero di active_transactions, poi distruggere il modello.

Basta tenere traccia del numero di transazioni già elaborati e innescare il distruggere l'ultimo richiamata in questo modo:

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

}

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top