如何在rails 3.1上使用coffeescript注册Jquery点击事件

How to register Jquery click event with coffeescript on rails 3.1(如何在rails 3.1上使用coffeescript注册Jquery点击事件)

本文介绍了如何在rails 3.1上使用coffeescript注册Jquery点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做看起来应该很简单的事情,但由于某种原因让我望而却步.我想将点击事件添加到我的 tasks.js 文件中的链接,如下所示:

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

这呈现为:

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

我想要的只是:

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

我如何使用 coffescript 和 rails 3.1 堆栈来实现这一点?

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

推荐答案

Coffee 应该将你所做的一切都包装在一个有限的范围内,这样你就不会用全局变量填充世界.这很有用,除非你有,否则不要忽略它.在顶层,您可以使用 this.something = "value" 导出.

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".

现在您上面的代码不起作用,因为在没有参数时函数调用需要一个括号.这将使两个片段在功能上相同.函数是 JavaScript 中的变量,因此它只是假设您想要返回该函数而不是没有括号的结果.

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

最后,Coffee 函数总是返回函数的最后一个值.这就是它的工作原理.所以不用担心 return 语句,你总是可以忽略结果.

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.

这篇关于如何在rails 3.1上使用coffeescript注册Jquery点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在rails 3.1上使用coffeescript注册Jquery点击事件

基础教程推荐