What's the best way to chain methods in CoffeeScript? For example, if I have this JavaScript how could I write it in CoffeeScript?
var req = $.get('foo.htm')
.success(function( response ){
// do something
// ...
})
.error(function(){
// do something
// ...
});
There are two approaches you can take: The best "literal" translation to CoffeeScript is (in my opinion)
The other approach is to move the inline functions "outline," a style that Jeremy Ashkenas (the creator of CoffeeScript) generally favors for non-trivial function arguments:
The latter approach tends to be more readable when the
success
anderror
callbacks are several lines long; the former is great if they're just 1-2 liners.I sometimes prefer having fewer parentheses as opposed to chaining, so I'd modify Trevor's last example:
Using the latest CoffeeScript, the following:
...compiles to:
As of Coffeescript 1.7, chaining has been significantly simplified, and you shouldn't need any of the parens-related workarounds mentioned here. Your above example can now be written as
Which compiles to
You can see an explanation of this and other CS 1.7 features here: https://gist.github.com/aseemk/8637896