1

I have defined a function in the coffeescript file as:

showAlert = () ->
  alert("asdfsd")

And from view i call this function as:

:javascript
  jQuery(function(){
   showAlert();
  });

But the function is not triggering. What is wrong here?

2
  • Does simply showAlert() work? Commented Jul 28, 2013 at 12:19
  • @alex yes! when I remove the function and put the code inside jQuery function. Commented Jul 28, 2013 at 12:24

1 Answer 1

1

This is because Coffeescript automatically wraps its transpiled Javascript output in an Immediately-Invoked Function Expression (IIFE), which means any functions you declare within a Coffeescript block are not in the global scope. Thus, your jQuery block can't find the showAlert function, because it doesn't exist in a scope/closure your jQuery block can access.

What you can do (though I'm not sure it's a great idea) is declare your "global" function on the window namespace:

window.showAlert = -> alert('asdfasdf')

And invoke it from your jQuery block:

javascript:
  jQuery(function($){
    window.showAlert();
  });

This will work because the window namespace is available in all (browser) scopes.

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

Comments

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.