Created
April 25, 2014 20:41
-
-
Save creage/11302561 to your computer and use it in GitHub Desktop.
jQuery.eachDeferred
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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