Skip to content

Instantly share code, notes, and snippets.

@donabrams
Created October 21, 2011 13:34
Show Gist options
  • Select an option

  • Save donabrams/1303862 to your computer and use it in GitHub Desktop.

Select an option

Save donabrams/1303862 to your computer and use it in GitHub Desktop.
Deferred Stack with functions all taking the same arguments (interceptor stack really).
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