Translating jQuery to Coffeescript

邮差的信 提交于 2019-12-13 06:49:54

问题


I posted a confusing question before. Long story short, I have a bit of jQuery working close to the way I want, but I cannot for the life of me get it to work in CoffeeScript.

When I try it different ways in CS the "on search" event triggers as soon as the page is loaded. I can't get it to just attach to the dataTable as I do in jQuery.

I'm sure it's something simple and dumb.

Here's the code:

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

    $('#customers')
            .on( 'search.dt',  function () { $('.nested_indent').hide(); } )

} );

The most recent CS version is here (the one that trips every time the page loads.)

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

回答1:


There are 2 differences towards the end from the JavaScript version:

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

The first is the . before $('#customers'). This attempts to use $ as a method rather than a global. You'll want to remove the . and insert a line break with matching indentation.

The second is that the function that was around $('.nested_indent').hide() is missing. You'll have to include at least -> to define one, as you have with jQuery ->.

)  # 1) separate statements with line break

$('#customers').on( 'search.dt', ->  # 2) wrap `hide` in a `function`
     $('.nested_indent').hide() )

The 2nd difference is why you're seeing:

[...] the "on search" event triggers as soon as the page is loaded.

Without the ->, the .hide() statement is being called immediately and its return value is being passed to .on(), so it isn't actually bound to the event.




回答2:


The problem is not that the event is getting triggered on page load, but that you are passing $('.nested_indent').hide() is getting run on page load because you are not passing it in a function in your CS as you are doing in your JavaScript.

What you want is:

jQuery ->
    $('#customers').dataTable(
        "sPaginationType": "bootstrap"
        "aaSorting": []
        "ordering": false
    );  

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


来源:https://stackoverflow.com/questions/24704610/translating-jquery-to-coffeescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!