How to register Jquery click event with coffeescript on rails 3.1

21,670

Solution 1

Coffee is supposed to wrap everything you do in a limited scope so you don't populate the world with globals. This is useful, unless you have, don't ignore this. At the top level, you can export with a this.something = "value".

Now your code above doesn't work because function calls need a paren when there are no parameters. This will make the two snip-its functionally the same. Functions are variables in JavaScript, so it just assumes you want to return that function instead of it's result without the parens.

$ ->
  $('.cancel_task').click -> 
    $('#task_form').toggle()

Lastly, a Coffee function always returns the last value of the function. It's just how it works. So don't worry about the return statements, you can always ignore the results.

Solution 2

The second snippet you posted is the correct output from coffee, and the second and last snippets you posted are (in practical terms) functionally equivalent. If you want you can get rid of the top-level closure by using coffee's --bare option (this is documented) but otherwise you should not fret about CoffeeScript's output unless it's causing you problems.

Share:
21,670
Beau
Author by

Beau

Updated on October 06, 2020

Comments

  • Beau
    Beau over 3 years

    I am trying to do what seems like it should be simple, but for some reason is eluding me. I want to add a click event to a link in my tasks.js file like so:

    $ ->
      $('.cancel_task').click -> 
        $('#task_form').toggle
    

    This renders out as:

    (function() {
      $(function() {
        return $('.cancel_task').click(function() {
        return $('#task_form').toggle;
      });
    });
    }).call(this);
    

    All I want is something like:

    $('.cancel_task').click(function()
    {
      $('#task_form').toggle();
    });
    

    How do i accomplish this with coffescript and the rails 3.1 stack?

  • Beau
    Beau over 12 years
    The problem is it is not working. Any ideas why that would be
  • Jordan Running
    Jordan Running over 12 years
    Debug it like you would any other JavaScript. Is jQuery loaded (I assume that's where $ is coming from)? Is your event firing? Is your event listener being registered? Are your selectors correct? Just follow the same steps you would if it was plain JavaScript, i.e. using breakpoints in Firebug/Web Inspector or just console.log.
  • Ostemar
    Ostemar over 12 years
    No it is not true that you can always ignore the results. I just ran into this. I had click() hooked up on a checkbox. Among other things the click was toggling a boolean by variable = !variable. This was placed last in the function. This lead to strange behaviors of course, causing the user to need to click twice to toggle the checkbox. Therein lies the danger of not having to use an implicit return.