Why does the Rails 3.1 / Sprockets 2 / CoffeeScript add additional code?

Working with Rails 3.1 (rc5), and I notice that any coffeescript file in which I include rails (or asterisks) adds to the top and bottom of javascript initialization. In other words, an empty .js.coffee file is displayed, which looks like this:

(function() { }).call(this); 

This is annoying because it spins the area of ​​my javascript (if I really don't know what I'm doing). I generally separate all of my javascript classes into separate files, and I believe that having this function code to complete my classes just pulls them out of scope from each other. Or at least I cannot access them, as I constantly get undefined errors.

Is there a way to override this? This stargazer file seems to be related to the addition of this code: https://github.com/sstephenson/sprockets/blob/master/lib/sprockets/jst_processor.rb

I understand that wrapping everything in a function may seem like an additional convenience, since then nothing starts until the DOM is loaded, but as far as I can tell, it just messed up my area.

+4
source share
2 answers

Are you going to place your objects in a global scope? I think that CoffeeScript usually wraps code with anonymous functions so that it does not accidentally pass variables into the global scope. If there is no way to disable it, the best option would probably be to add something that you want to be in the global area to the window object:

 window.myGlobal = myGlobal; 

It seems that these days it is best to use javascript to put the code inside the function area and be explicit about adding objects to the global area, and this is what I usually see automatically in CoffeeScript.

+10
source

You do not want to invest everything in the global sphere. You need a module or module similar to a system where you can create namespaces so you don't mix with other libraries. Read

https://github.com/jashkenas/coffee-script/wiki/Easy-modules-with-coffeescript

+2
source

All Articles