CoffeeScript always returns in anonymous function

前端 未结 2 1404
余生分开走
余生分开走 2021-01-14 02:29

I\'m trying to write some CoffeScript function which checks all checkboxes in a table upon checking the checkbox in the th.

My function in CoffeeScript looks like th

相关标签:
2条回答
  • 2021-01-14 02:37

    If you just use return (or, equivalently, undefined) as the last line of a function, the CoffeeScript compiler will give you JS with no return at all. So the most efficient way of writing your code would be

    $("table.tableview th input:checkbox").live 'click', -> 
      checkedStatus = this.checked
      $("table.tableview tbody tr td:first-child input:checkbox").each ->
        this.checked = checkedStatus
        return
      return
    

    (You can safely do without the second return, of course. Only a return value of false has an effect in jQuery.)

    There was also a proposed syntax (-/>) for defining a function with no return value; see issue 899.

    0 讨论(0)
  • 2021-01-14 02:39

    Just add a true as the last line of your function, and coffeescript will compile the JS to return that instead:

    $("table.tableview th input:checkbox").live 'click', -> 
        checkedStatus = this.checked
        $("table.tableview tbody tr td:first-child input:checkbox").each ->
            this.checked = checkedStatus
        true
    

    In other words, CoffeeScript always returns the result of the last line (like Ruby does)


    Edit (after the question was updated):

    Again, you can't keep CoffeeScript from returning the value of the last line in a function - part of the point of CoffeeScript is that it does exactly that.

    CoffeeScript has significant whitespace, so indentation is what says what belongs together - your example is is actually correct:

    $("table.tableview th input:checkbox").live 'click', -> 
        checkedStatus = this.checked
        $("table.tableview tbody tr td:first-child input:checkbox").each ->
            this.checked = checkedStatus
            true // cause this function (the each-iterator) to return true
        true // causes the click handler function to return true
    

    There's no difference between this and just writing return true in a function like you would in javascript. You just use whitespace instead of {} to make code blocks.

    0 讨论(0)
提交回复
热议问题