Javascript 如何在rails 3.1上使用coffeescript注册Jquery点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7669246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to register Jquery click event with coffeescript on rails 3.1
提问by Beau
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:
我正在尝试做看起来应该很简单的事情,但由于某种原因,我无法做到。我想向我的 tasks.js 文件中的链接添加一个点击事件,如下所示:
$ ->
$('.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?
我如何使用 coffescript 和 rails 3.1 堆栈完成此操作?
回答by Travis
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"
.
咖啡应该将您所做的一切都包装在有限的范围内,这样您就不会用全局变量填充世界。这很有用,除非你有,否则不要忽略这一点。在顶层,您可以使用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.
现在你上面的代码不起作用,因为函数调用在没有参数时需要一个括号。这将使两个 snip-it 在功能上相同。函数是 JavaScript 中的变量,所以它只是假设你想返回那个函数而不是没有括号的结果。
$ ->
$('.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.
最后,Coffee 函数总是返回函数的最后一个值。这就是它的工作原理。所以不用担心return
语句,你可以随时忽略结果。
回答by Jordan Running
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.
您发布的第二个片段是 的正确输出coffee
,您发布的第二个和最后一个片段(实际上)在功能上是等效的。如果您愿意,您可以使用coffee
's--bare
选项(已记录)摆脱顶级闭包,否则您不应该担心 CoffeeScript 的输出,除非它给您带来问题。