Question

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:

(function() {
    var someFunc;
    someFunc = function() {
       return alert("hello");
    };
}).call(this); 

and in this case I cant call it. I have not found any proper configurations in the plugin documentation to avoid using anonymous functions while compiling coffee-file. How can I solve this?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top