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?

2
  • I don't know, I just saw this and... wanted some coffee... Commented May 19, 2011 at 14:15
  • The second part of this question is basically a duplicate of stackoverflow.com/questions/5211638/… 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.) Commented May 19, 2011 at 15:50

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.