Method chaining with function arguments

nicholaides picture nicholaides · Feb 28, 2011 · Viewed 16.8k times · Source

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
    // ...
  });

Answer

a paid nerd picture a paid nerd · May 10, 2011

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();
});