2

Using coffeescript, jQuery, and sprockets in rails 3.1 the coffeescript files are compiled in to blocks like:

(function() {
 var a;
 var b;
 var c;
 foo = function() { 
  alert("foo");
 }
 bar = function() {
  alert("bar");
 }

}).call(this);

This seems to move functions foo and bar out of global scope, so bar can be called by foo, but neither can be called from the html code. When I try to call foo from a select onchange element, I get a "Can't find variable: foo".

The workaround right now is to move all globally available functions to .js files. But what's the right way to do this?

Thanks

MrJoshua
  • 43
  • 3
  • 1
    I do it the same as Dogbert, you might want to check this out for other options (including this one) http://vimeo.com/24391448 – house9 Jul 13 '11 at 20:49

1 Answers1

5

I prefer declaring a top level object (for namespacing), and attaching all the functions that I'll need access to, to it.

At the top of your file, add something like

window.App = window.App || {};

Then declare your functions

var foo = function() { ... };
var bar = function() { ... };

Lastly, export functions needed

window.App.foo = foo;

Somewhat related info - "Can't find variable" error with Rails 3.1 and Coffeescript

Community
  • 1
  • 1
Dogbert
  • 212,659
  • 41
  • 396
  • 397