Created
October 21, 2011 13:34
-
-
Save donabrams/1303862 to your computer and use it in GitHub Desktop.
Deferred Stack with functions all taking the same arguments (interceptor stack really).
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
| define(["jquery/1.5.1/jquery"], function($) { | |
| // | |
| // This function executes a list of promise returning functions all given the same args | |
| // If you specify a scope, the list may contain string names instead of function references. | |
| // It returns a Promise | |
| // | |
| var executeDeferredStack = $.executeDeferredStack = function(functionStack, args, scope) { | |
| var dfd = $.Deferred(); | |
| var lastFunc = function() { | |
| dfd.resolve(arguments); | |
| }; | |
| var failFunc = function() { | |
| dfd.fail(arguments); | |
| }; | |
| var scope = scope || this; | |
| if (functionStack && functionStack.length) { | |
| //copy and reverse the stack. | |
| var stack = functionStack.slice(0).reverse(); | |
| for (var i = 0;i < stack.length;i++) { | |
| var f = lastFunc; | |
| lastFunc = function() { | |
| if ($.isFunction(stack[i])) { | |
| stack[i].apply(scope, args).then(f, failFunc); | |
| } else { | |
| scope[stack[i]].apply(scope, args).then(f, failFunc); | |
| } | |
| }; | |
| }; | |
| } | |
| lastFunc(); | |
| return dfd.promise(); | |
| }; | |
| return executeDeferredStack; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment