Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the heck is Rails 3.1 / Sprockets 2 / CoffeeScript adding extra code?

Working with Rails 3.1 (rc5), and I'm noticing that any coffeescript file I include rails (or sprockets) is adding in initializing javascript at the top and bottom. In other words, a blank .js.coffee file gets outputted looking like this:

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

This is irritating because it screws up my javascript scope (unless 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 that function code wrapping my classes just puts them out of scope from one another. Or, atleast, I can't seem to access them as I am continually getting undefined errors.

Is there a way to override this? It seems like this file in sprockets has to do with adding this code: https://github.com/sstephenson/sprockets/blob/master/lib/sprockets/jst_processor.rb

I understand that wrapping everything in a function might seem like an added convenience as then nothing is ran until DOM is loaded, but as far as I can tell it just messes up my scope.

like image 474
Conrad VanLandingham Avatar asked Dec 16 '22 11:12

Conrad VanLandingham


2 Answers

Are you intending to put your objects into the global scope? I think CoffeeScript usually wraps code in anonymous functions so that it doesn't accidentally leak variables into the global scope. If there's not a way to turn it off, your best bet would probably be to specifically add anything you want to be in the global scope to the window object:

window.myGlobal = myGlobal;

It seems to be a javascript best practice these days to put code inside a function scope and be explicit about adding objects to the global scope, and it's something I usually see CoffeeScript do automatically.

like image 161
Justin Weiss Avatar answered Dec 18 '22 23:12

Justin Weiss


You don't want to put everything into the global scope. You want a module or module like system where you can namespace things so you don't colide with other libraries. Have a read of

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

like image 22
bradgonesurfing Avatar answered Dec 18 '22 23:12

bradgonesurfing