将jQuery转换为Coffeescript

我之前发过一个令人困惑的问题。 长话短说,我有一点jQuery工作接近我想要的方式,但我不能为我的生活让它在CoffeeScript中工作。

当我在CS中尝试不同的方式时,“on search”事件会在加载页面后立即触发。 我不能像在jQuery中那样只是附加到dataTable。

我确信这是简单而愚蠢的事情。

这是代码:

$(document).ready(function() { $('#customers').dataTable( { "sPaginationType": "bootstrap", "aaSorting": [], "ordering": false } ); $('#customers') .on( 'search.dt', function () { $('.nested_indent').hide(); } ) } ); 

最新的CS版本在这里(每次加载页面时都会跳转。)

 jQuery -> $('#customers').dataTable( "sPaginationType": "bootstrap" "aaSorting": [] "ordering": false ).$('#customers').on( 'search.dt', $('.nested_indent').hide() ) 

JavaScript版本有两个不同之处:

 ).$('#customers').on( 'search.dt', $('.nested_indent').hide() ) 

首先是.$('#customers') 。 这会尝试使用$作为方法而不是全局。 你想要删除. 并插入带有匹配缩进的换行符。

第二个是缺少$('.nested_indent').hide()周围的function 。 你必须至少包括->来定义一个,就像你使用jQuery ->

 ) # 1) separate statements with line break $('#customers').on( 'search.dt', -> # 2) wrap `hide` in a `function` $('.nested_indent').hide() ) 

第二个区别是你看到的原因:

[…]“on search”事件会在加载页面后立即触发。

如果没有-> ,则立即调用.on() .hide()语句,并将其return值传递给.on() ,因此它实际上并未绑定到该事件。

问题不在于事件是在页面加载时被触发,而是你传递了$('.nested_indent').hide()在页面加载时运行,因为你没有在CS中的函数中传递它正在用你的JavaScript做。

你想要的是:

 jQuery -> $('#customers').dataTable( "sPaginationType": "bootstrap" "aaSorting": [] "ordering": false ); $('#customers').on 'search.dt', -> $('.nested_indent').hide()