开发者

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_fo开发者_如何学Crm').toggle();
});

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜