Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery deferred with .each()

Any ideas how you might use JQuery's deferred methods with a function that detects all changed forms and submits each one as an Ajax post?

I can get the same thing working if I just list a load of form submissions but if I use...

$('form.changed').each(function(){
  return $(this).submitWithAjax();
});

A fuller version of the code that I'm trying to get working is here... at JS Fiddle

Thanks in advance!

like image 835
Kevin Monk Avatar asked May 28 '11 16:05

Kevin Monk


1 Answers

Instead of ".each()", use ".map()":

var deferreds = $('form.changed').map(function(i, elem) {
  return $(this).submitWithAjax();
});

$.when.apply(null, deferreds.get()).then(function() { ... });

The "$.when()" thing lets you bundle up a bunch of deferred objects and wait for all of them to succeed (or for any to fail — note the difference there). It normally allows an arbitrary number of arguments, but since we've got an array I used "apply()".

Note that I've only used this stuff lightly, so read the jQuery API docs to double check :-) edit — also upon re-reading your question, I may have misunderstood you.

like image 54
Pointy Avatar answered Oct 22 '22 16:10

Pointy