functions in coffee-file are not available from other js

后端 未结 1 476
南方客
南方客 2021-01-17 01:42

I try to use coffeescript in my Grails-project. To achive this I decided to use coffeescript-resources plugin. But compiled coffee in result view looks like follows:

相关标签:
1条回答
  • 2021-01-17 02:49

    From the fine manual:

    Lexical Scoping and Variable Safety
    [...]
    Although suppressed within this documentation for clarity, all CoffeeScript output is wrapped in an anonymous function: (function(){ ... })(); This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident.

    If you'd like to create top-level variables for other scripts to use, attach them as properties on window, or on the exports object in CommonJS. The existential operator (covered below), gives you a reliable way to figure out where to add them; if you're targeting both CommonJS and the browser: exports ? this

    So that self-invoking function wrapper exists to prevent you from polluting the global namespace. If you want to put something into the global namespace then you have to put it there explicitly; in a browser, you can do that using:

    window.someFunc = -> alert('hello')
    

    or

    @someFunc = -> alert('hello')
    

    The @someFunc form assumes that you're at the top of the scope (i.e. not inside another function or class).

    Alternatively, you could find a way to compile your CoffeeScript with --bare:

    -b, --bare
    Compile the JavaScript without the top-level function safety wrapper.

    0 讨论(0)
提交回复
热议问题