How to make one AJAX request after saving multiple base

I have a situation where I need to save the Backbone model, and then its success iterating through the collection and saving them, and then at each of these successes iterating through the other collection and saving them, and then after they are all executed AJAX request . This is what I have:

backboneModel.save( {}, { wait: true, success: function (model1, response1) { $.each(backboneCollection1.models, function () { this.save( {}, { wait: true, success: function (model2, response2) { $.each(backboneCollection2.models, function () { this.save( {}, { wait: true, success: function (model2, response2) { //If i put the AJAX request here it will happen for every iteration which is not desired } }); }); } }); }); //If i put the AJAX request here it will fire after one iteration of the first each even with async set to false on the AJAX request } }); 

Does anyone have any suggestions on where to execute this AJAX request so that it runs only once after all the base models have been stored on the server?

+4
source share
2 answers

Take a look at the jsfiddle I created. It replaces your callbacks and uses promises to save your model, then collect 1, and then collect 2. After all this is done, you can make your ajax call in done ().

The bulk of the changes are replacing what you have above.

 var saveEverything = backboneModel.save() .pipe(function() { return saveCollection(backboneCollection1); }) .pipe(function() { return saveCollection(backboneCollection2); }); saveEverything.done(function() { console.log('done with everything, ajax time') });//make your ajax call in the done 

If you have no idea what jQuery promises are, this is a really great blog post explaining promises. If my example does not make sense at all, just ask, I can try to explain what is happening and what is happening.

+2
source

Count when you repeat models, and when your count = model length, call AJAX

0
source

Source: https://habr.com/ru/post/1442369/


All Articles