jQuery用Rails/Coffeescript绑定事件?

Moh*_*bid 12 javascript ruby-on-rails coffeescript

所以在app/assets/javascript/faye.js.coffee.erb我有以下内容:

$('#room_tag').bind('blur', () ->
   alert('Hey!')
)
Run Code Online (Sandbox Code Playgroud)

其中的所有其他代码如:sendmessage('room', 'message')工作得很好.我可以复制并粘贴从上面的块生成的代码并将其粘贴到Chrome中,它可以正常工作.我认为这是因为,无论是rails还是coffeescript?,无论是其中之一,都将整个文件包装在:

(function() {
  // your generated code here
}).call(this);
Run Code Online (Sandbox Code Playgroud)

还有可能我有办法访问那里定义的方法吗?是否可以在那里定义一个方法而不将其分配给变量?

Pet*_*ons 29

1).bind在文档准备好之前,很可能你的调用过早执行,因此它没有做任何事情.把它包在一个调用$(document).ready喜欢这个

    $(document).ready ->
      $('#room_tag').bind 'blur', ->
        alert 'Hey!'
Run Code Online (Sandbox Code Playgroud)

实际上有一个可爱的快捷方式,因为jQuery的默认$函数是别名$(document).ready,你可以这样做:

$ ->
  $('#room_tag').bind 'blur', ->
    alert 'Hey!'
Run Code Online (Sandbox Code Playgroud)

2)coffeescript将所有内容包装在自执行函数定义中.

3)如果要在coffeescript中创建全局函数,请将其显式指定为全局窗口对象的属性

    window.myFunc = (arg1) ->
      alert arg1
Run Code Online (Sandbox Code Playgroud)

2)和3)在CoffeeScript文档中清楚地解释