简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM