Created
April 25, 2014 20:43
-
-
Save creage/11302611 to your computer and use it in GitHub Desktop.
$.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) { | |
$.extend({ | |
/* | |
* Iterates over elms array/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 (elms, c) { | |
if (!$.isArray(elms)) { | |
elms = $.makeArray(elms); | |
} | |
var that = this, | |
dfd = $.Deferred(), | |
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, 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