Method chaining with function arguments

前端 未结 4 1560
囚心锁ツ
囚心锁ツ 2021-01-30 12:40

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\')
         


        
4条回答
  •  花落未央
    2021-01-30 13:11

    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

提交回复
热议问题