2011-08-12 115 views
4

我正试图编写一些CoffeScript函数,它检查表中的复选框时检查表中的所有复选框。CoffeeScript总是返回匿名函数

我在CoffeeScript的功能如下:

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

它的伟大工程,用于检查所有的箱子。但是,取消选中时不起作用。编译的JS如下所示:

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

它不起作用,因为在第一个设置为false之后,该函数的返回值将为false。然而,我不知道如何抑制咖啡脚本的这种默认返回行为。请帮忙。

当我添加一个“真”按Flambino的建议,我得到以下JS

$("table.tableview th input:checkbox").live('click', function() { 
    var checkedStatus; 
    checkedStatus = this.checked; 
    $("table.tableview tbody tr td:first-child input:checkbox").each(function() { 
     return this.checked = checkedStatus; 
    }); 
    return true; 
    }); 

我可以得到函数内的return语句,唯一的办法是把它所有的方式是这样的:

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

我在做什么错? Thx的帮助迄今为止

回答

5

只需添加一个true为你的函数的最后一行,并CoffeeScript的将编译JS以返回代替:

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

换句话说,CoffeeScript的总是返回的结果最后一行(像Ruby一样)


编辑(这个问题是更新后):

同样,您不能让CoffeeScript不返回函数中最后一行的值 - CoffeeScript的一部分就是它完全做到这一点。

CoffeeScript的有显著的空白,所以缩进什么说什么属于一起 - 你的例子实际上是正确的:

$("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 

有这一点,只是在一个函数写return true,就像您在JavaScript之间没有差异。您只需使用空白而不是{}来制作代码块。

+0

是的。看起来不像有一种方法可以抑制咖啡文本返回行为。 https://开头github上。com/jashkenas/coffee-script/issues/1401 – olooney

+0

我修改了原帖 – Gidogeek

+0

@Gidogeek:我已经更新了我的答案:) – Flambino

19

如果您只是使用return(或等同于undefined)作为函数的最后一行,那么CoffeeScript编译器将根本没有为您提供return的JS。因此,编写代码的最有效的方法是

$("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 

(您可以放心地做没有第二return,当然,只有false一个返回值jQuery中的作用。)

有还提供用于定义没有返回值的函数的建议语法(-/>);见issue 899