Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register Jquery click event with coffeescript on rails 3.1

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?

like image 377
Beau Avatar asked Oct 06 '11 00:10

Beau


2 Answers

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.

like image 147
Travis Avatar answered Nov 04 '22 02:11

Travis


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.

like image 1
Jordan Running Avatar answered Nov 04 '22 03:11

Jordan Running