javascript jQuery 使用 Rails/Coffeescript 绑定事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6060051/
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
jQuery bind events with Rails/Coffeescript?
提问by Mohammad El-Abid
So in app/assets/javascript/faye.js.coffee.erb
I have the following:
所以在app/assets/javascript/faye.js.coffee.erb
我有以下内容:
$('#room_tag').bind('blur', () ->
alert('Hey!')
)
All the other code in it such as: sendmessage('room', 'message')
work just fine. And I can copy and paste the code generated from the block above and paste it into Chrome it works fine. I assume this is because, is it rails or coffeescript?, either way one of them, wraps the entire file in:
其中的所有其他代码,例如:sendmessage('room', 'message')
工作正常。我可以复制并粘贴从上面的块生成的代码并将其粘贴到 Chrome 中,它工作正常。我认为这是因为,它是 rails 还是 coffeescript?,无论哪种方式,都将整个文件包装在:
(function() {
// your generated code here
}).call(this);
Also would there happen to be a way for me to access methods that are defined within there? Is it possible to define a method in there without assigning it to a variable?
是否还有一种方法可以让我访问其中定义的方法?是否可以在其中定义方法而不将其分配给变量?
回答by Peter Lyons
1) Most likely your .bind
call is executing too soon, before the document is ready and thus it doesn't do anything. Wrap it in a call to $(document).ready
like this
1) 很可能您的.bind
调用在文档准备好之前执行得太快了,因此它什么也没做。把它包装在一个$(document).ready
像这样的电话中
$(document).ready ->
$('#room_tag').bind 'blur', ->
alert 'Hey!'
And there's actually a cute shortcut for this since jQuery's default $
function is an alias for $(document).ready
, you can just do:
实际上有一个可爱的快捷方式,因为 jQuery 的默认$
函数是 的别名$(document).ready
,你可以这样做:
$ ->
$('#room_tag').bind 'blur', ->
alert 'Hey!'
2) It is coffeescript that wraps everything in a self-executing function definition.
2) 将所有内容包装在自执行函数定义中的是coffeescript。
3) If you want to make a global function in coffeescript, explicitly assign it as a property of the global window object
3)如果要在coffeescript中做一个全局函数,显式赋值为全局window对象的一个属性
window.myFunc = (arg1) ->
alert arg1
2) & 3) are clearly explained in the CoffeeScript docs
2) & 3) 在CoffeeScript 文档中有清楚的解释