12

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?

Myles Best
  • 1,177
  • 1
  • 9
  • 17
  • I don't know, I just saw this and... wanted some coffee... – pixelbobby May 19 '11 at 14:15
  • The second part of this question is basically a duplicate of http://stackoverflow.com/questions/5211638/pattern-for-coffeescript-modules/ See my answer there, explaining the wrapper's purpose. (Though in this case, the wrapper isn't causing the issue, as Peter says in his answer.) – Trevor Burnham May 19 '11 at 15:50

1 Answers1

29

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

    $(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:

$ ->
  $('#room_tag').bind 'blur', ->
    alert 'Hey!'

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

    window.myFunc = (arg1) ->
      alert arg1

2) & 3) are clearly explained in the CoffeeScript docs

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • From the Coffee Docs `The usual caveats about CoffeeScript apply — your inline scripts will run within a closure wrapper, so if you want to expose global variables or functions, attach them to the window object.` – Caley Woods May 19 '11 at 14:54
  • Exactly, sounds like #1 is the answer here. You can confirm this by checking `$('#room_tag').length`. If it's `1`, the element exists at the time of the selection; if it's `0`, it doesn't. – Trevor Burnham May 19 '11 at 15:53