Skip to content

Instantly share code, notes, and snippets.

@jasonwyatt
Created December 21, 2009 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonwyatt/261260 to your computer and use it in GitHub Desktop.
Save jasonwyatt/261260 to your computer and use it in GitHub Desktop.
/**
* Permanently bind a function to an object.
*
* @param fn (function)
* Function to bind.
* @param object (object)
* Object scope to force the function to run within.
* @return
* New function, where the argument function is forced to
* execute within the scope of object.
*/
function bind(fn, object){
return function(){
return fn.apply(object, arguments);
};
}
/**
* Chain one function to another so that the second is called
* after the first one finishes and is given the result of the
* first.
*
* @param fn1 (function)
* First function to call, it's result will be passed on to
* fn2.
* @param fn2 (function)
* Function to call with the results of the first function.
* @param waitTime (optional integer)
* Time to wait between when the first function finishes and
* when to start the second.
* @return
* New function which, when called with the arguments you'd
* want to call fn1 with, will initiate the chain.
*/
function chain(fn1, fn2){
var waitTime = arguments.length > 2 ? arguments[2] : 10;
return function(){
var returnObj = fn1.apply(null, arguments);
var obj2 = obj2;
setTimeout(function(){
fn2.call(null, returnObj);
}, waitTime);
return returnObj;
};
}
/**
* Chain together a bunch of functions which will call
* eachother and pass along their return values.
*
* @param scope (object or null)
* The scope within which to call all of the functions.
* @param fns (Array of Functions)
* The functions to make a non-blocking sequence out of.
* @param waitTime (optional integer)
* The amount of time to wait between each function.
* @return
* A new function which consists of the sequence of functions.
* Call it with the arguments you'd want to pass to the first
* function in the sequence.
*/
function makeSequence(scope, fns){
var waitTime = arguments.length > 2 ? arguments[2] : 10;
for(var i = 0, len=fns.length; i < len; i++){
fns[i] = bind(fns[i],scope);
}
for(var len=fns.length, i=len-1; i >= 1; i--){
fns[i-1] = chain(fns[i-1], fns[i], waitTime);
}
return fns[0];
}
/***************************************************************
* Example Situation.
**************************************************************/
function addOne(){
console.log("addOne()->1+"+this.value);
this.value++;
return;
}
var obj = {
name:"Chained object scope",
value: 1
};
var start = makeSequence(obj, [addOne, addOne, addOne, addOne], 200);
start(); // start execution
console.dir(obj);
setTimeout(function(){
console.dir(obj);
}, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment