Translating jQuery to Coffeescript

2019-09-05 06:30发布

问题:

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()