Skip to content

Instantly share code, notes, and snippets.

@creage
Created April 25, 2014 20:41
Show Gist options
  • Save creage/11302561 to your computer and use it in GitHub Desktop.
Save creage/11302561 to your computer and use it in GitHub Desktop.
jQuery.eachDeferred
(function ($, window, document, undefined) {
$.fn.extend({
/*
* Iterates over jQuery object collection using deferred callbacks.
* the function assigned for iterator should return promise.
* resolved promises notify the main deferred, so we can track each loop result.
* returns promise.
*/
eachDeferred: function (c) {
var that = this,
dfd = $.Deferred(),
elms = $.makeArray(that),
i = elms.length,
next = function () {
setTimeout(function () { elms.length ? cb(elms.shift()) : dfd.resolve(that); }, 0);
},
cb = function (elm) {
$.when(c.call(elm, i - elms.length, typeof elm == 'string' ? elm : $(elm))).always(function (result) {
dfd.notify(result);
next();
});
};
next();
return dfd.promise();
},
});
}(jQuery, window, document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment