Reputation: 996
I'm writing CoffeeScript inside a Ruby on Rails 3.2.13 project, but it seems to compile to an improper JavaScript. My code is:
$('#a').change () ->
$('#b').hide()
The coffeescript.org online compiler compiles it as:
$('#a').change(function() {
return $('#b').hide();
});
Whereas for some reason when my project runs in the development environment compiles it as:
(function() {
$('#a').change(function() {
return $('#b').hide();
});
}).call(this);
What's the reason behind this? And Does it have any implication?
Edit
In extension to edovic's answer, I found the answer to how can I use option “--bare” in Rails 3.1 for CoffeeScript
Upvotes: 1
Views: 84
Reputation: 8846
Like @edofic noted, Coffeescript is just wrapping your code in a function to shield it from the outside world.
To get around this, I just prefix all of my globals with window (eg: window.someVar) when I declare them. This makes them accessible outside of the code and also makes the Coffeescript more portable so that you can compile it on other machines that are not setup to use the --bare option.
Upvotes: 1
Reputation: 727
It's just wrapping everything up in a function to "shield" it from the global scope. You can use the coffeescript compiler manually. Compile normally and you'll get the bottom output, add -bare
flag and you'll get the top one. See Getting rid of CoffeeScript's closure wrapper
Upvotes: 2