->snip<-

Random code snippets, going ons, and random other things. Enjoy!

Monday, December 3, 2007

Javascript function chaining

After using jQuery a bit, I fell in love with their concept of chaining. After having written various function calls over and over again, but with different parameters, I came up with a way to wrap a function so that it returns itself, and can be called again without having to do any extra work. The code:


/*(CC)Creative Commons Share-alike 3.0, Dan Sheadel*/
Function.prototype.chain=function(){
var original=this
this.apply(this,arguments)//call with original arguments
//wrap function to return the wrapper function
var f=function(){
original.apply(original,arguments)
return f
}
return f
}

// and use with a call like this:
someFunction.chain(arg1,arg2)(arg1)(arg1,arg2,arg3)
// which will call someFunction three times, with the different arguments.

// this is far more useful when using anonymous functions...
(function(a){alert(a)}).chain('hey')('look')('at')('that')
//and other functions with throwaway return values

// I often use it for ajax calls, which in scripts, have meaningless returns,
// but have a very useful return when used in dom
ajax.chain(node_to_change,'http://url.com')(node1,url1)(node2,url2)//...

i like ajax functions to return an inverted success, so that the return
value can be directly used in links as onclick returns.
this way, a successful ajax run will return false, which disables the link
action on most browsers. On non javascript (or unsupported) browsers,
the link behaves normally.

It also tends to tidy up code, as the function name is written once, but called repeatedly.
But mostly, it results in a fun and organized looking function call.