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 // ... });
Method chaining, also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.
Method chaining is a technique that is used for making multiple method calls on the same object, using the object reference just once. Example − Assume we have a class Foo that has two methods, bar and baz. We create an instance of the class Foo − foo = Foo()
Method Chaining is the practice of calling different methods in a single line instead of calling other methods with the same object reference separately. Under this procedure, we have to write the object reference once and then call the methods by separating them with a (dot.).
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(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With