Method chain with function arguments

What is the best way to hook methods in CoffeeScript? For example, if I have this JavaScript, how can I write it in CoffeeScript?

var req = $.get('foo.htm') .success(function( response ){ // do something // ... }) .error(function(){ // do something // ... }); 
+64
javascript syntax coffeescript
Feb 28 '11 at 3:50 a.m.
source share
4 answers

Using the latest CoffeeScript , do the following:

 req = $.get 'foo.html' .success (response) -> do_something() .error (response) -> do_something() 

... compiles to:

 var req; req = $.get('foo.html').success(function(response) { return do_something(); }).error(function(response) { return do_something(); }); 
+70
May 10 '11 at 7:30 a.m.
source share

There are two approaches you can take: the best "literal" translation into CoffeeScript (in my opinion)

 req = $.get('foo.htm') .success((response) -> # do something ) .error( -> # do something ) 
Another approach is to move the built-in functions "outline", a style that Jeremy Ashkenas (creator of CoffeeScript) usually prefers non-trivial function arguments:
 onSuccess = (response) -> # doSomething onError = -> # doSomething req = $.get('foo.htm').success(onSuccess).error(onError) 

The latter approach tends to be more readable if the success and error callbacks are several lines long; the first is great if they are only 1-2 liners.

+37
Feb 28 '11 at 16:18
source share

I sometimes prefer to have fewer brackets rather than a chain, so I would change Trevor's last example:

 req = $.get 'foo.htm' req.success (response) -> # do something req.error -> # do something 
+11
Mar 02 '11 at 19:40
source share

As with Coffeescript 1.7, the chain has been greatly simplified, and you don't need any Parens-related workarounds mentioned here. Your example above can now be written as

 req = $.get 'foo.htm' .success ( response ) -> alert "success" .error -> alert "error" 

What compiles for

 var req; req = $.get('foo.htm').success(function(response) { return alert("success"); }).error(function() { return alert("error"); }); 

You can see an explanation of this and other CS 1.7 features here: https://gist.github.com/aseemk/8637896

+9
Feb 18 '14 at 16:25
source share



All Articles