0

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?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Vit Ias
  • 725
  • 4
  • 16
  • there is a pull-request for this feature (`--bare`), and for many other things, but plugin author stopped working on it. So, I recommend you to use standalone command line compile for coffeescript instead. – Igor Artamonov Oct 13 '13 at 06:40

1 Answers1

1

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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800