65

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
    // ...
  });
Community
  • 1
  • 1
nicholaides
  • 19,211
  • 12
  • 66
  • 82

4 Answers4

70

Using the latest CoffeeScript, 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();
});
a paid nerd
  • 30,702
  • 30
  • 134
  • 179
  • 2
    This is awesome. Thank you, a language that puts the operator first on the next line rather than awkward trailing syntaxes. Hooray! – Walt W Oct 31 '12 at 23:11
  • 2
    worth noting that the parens are no longer necessary around the 'foo.html' in Coffeescript 1.7 (see my answer below) – Ben McCormick Feb 18 '14 at 16:27
37

There are two approaches you can take: The best "literal" translation to CoffeeScript is (in my opinion)

req = $.get('foo.htm')
  .success((response) ->
    # do something
  )
  .error( ->
    # do something
  )

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:

onSuccess = (response) ->
  # doSomething

onError = ->
  # doSomething

req = $.get('foo.htm').success(onSuccess).error(onError)

The latter approach tends to be more readable when the success and error callbacks are several lines long; the former is great if they're just 1-2 liners.

Trevor Burnham
  • 76,828
  • 33
  • 160
  • 196
11

I sometimes prefer having fewer parentheses as opposed to chaining, so I'd modify Trevor's last example:

req = $.get 'foo.htm'
req.success (response) -> # do something
req.error -> # do something
Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
Amir
  • 4,131
  • 26
  • 36
9

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

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

Which compiles to

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

Ben McCormick
  • 25,260
  • 12
  • 52
  • 71