Jamal Abdul Nasir
Jamal Abdul Nasir

Reputation: 2667

Calling a function in coffeescript from inline script

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?

Upvotes: 1

Views: 179

Answers (1)

Daniel Wright
Daniel Wright

Reputation: 4604

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.

Upvotes: 1

Related Questions