如何在rails 3.1上注册带有coffeescript的Jquery点击事件 [英] How to register Jquery click event with coffeescript on rails 3.1
问题描述
我试图做的似乎应该很简单,但由于某种原因是逃避我。我想添加一个点击事件到我的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
>
This renders out as:
(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?
推荐答案
咖啡应该包装你在有限范围内做的一切,所以你不会使用全局变量填充世界。这是有用的,除非你有,不要忽视这个。在顶层,您可以使用 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()
最后,返回函数的最后一个值。这只是它的工作原理。所以不要担心 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点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!