jQuery 与 Rails/Coffeescript 绑定事件?
因此,在 app/assets/javascript/faye.js.coffee.erb
中,我有以下内容:
$('#room_tag').bind('blur', () ->
alert('Hey!')
)
其中的所有其他代码,例如: sendmessage('room', 'message')< /code> 工作得很好。我可以复制并粘贴从上面的块生成的代码并将其粘贴到 Chrome 中,效果很好。我认为这是因为,它是rails还是coffeescript?无论哪种方式,都将整个文件包装在:
(function() {
// your generated code here
}).call(this);
另外,是否有一种方法可以让我访问其中定义的方法?是否可以在其中定义一个方法而不将其分配给变量?
So in app/assets/javascript/faye.js.coffee.erb
I have the following:
$('#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:
(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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
1) 很可能您的
.bind
调用执行得太快,在文档准备好之前,因此它没有执行任何操作。将其包装在对$(document).ready
的调用中,实际上有一个可爱的快捷方式,因为 jQuery 的默认
$
函数是$( 的别名document).ready
,你可以这样做:2) 咖啡脚本将所有内容包装在一个自执行函数定义中。
3) 如果你想在coffeescript中创建一个全局函数,请显式地将其指定为全局窗口对象的属性
2) & 3) 在 CoffeeScript 文档 中有清楚的解释
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 thisAnd there's actually a cute shortcut for this since jQuery's default
$
function is an alias for$(document).ready
, you can just do:2) It is coffeescript that wraps everything in a self-executing function definition.
3) If you want to make a global function in coffeescript, explicitly assign it as a property of the global window object
2) & 3) are clearly explained in the CoffeeScript docs