Method chaining with function arguments

前端 未结 4 1559
囚心锁ツ
囚心锁ツ 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 12:52

    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.

提交回复
热议问题