"Cannot find variable" error with Rails 3.1 and Coffeescript

I have views in my application that reference my application.js file, which contains the functions that I use throughout the application.

I just installed the Rails 3.1 release candidate after using the release version 3.1. Until I installed RC, I had no problems, but now I get this error:

ReferenceError: cannot find variable: indicator_tag

indicator_tag is a function defined in application.js. The only difference I noticed in the javascript file is that now all my functions are wrapped in:

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

I understand that this is a variable scope? But can this prevent my pages from using these variables? And before anyone asks, I made sure the javascript paths are correct in my include tags.

+22
javascript ruby-on-rails coffeescript
May 22 '11 at 18:46
source share
2 answers

By default, each CoffeeScript file is compiled to close. You cannot interact with functions from another file unless you export them to a global variable. I would recommend doing something like this:

At the top of each coffeescript file add a line like

 window.Application ||= {} 

This will ensure the continued presence of the global Application.

Now for each function that you need to call from another file, define them as

 Application.indicator_tag = (el) -> ... 

and call them using

 Application.indicator_tag(params) 
+47
May 22 '11 at 19:34
source share

Dogbert's solution is a great way to go if you have a very complex JS server. However, there is a much simpler solution if you have only a few functions that you work with. Just add them directly to the window object, for example:

 window.indicator_tag = (el) -> ... 

Then you can use your functions from anywhere without reducing them to another object.

+12
Sep 06 2018-11-11T00:
source share



All Articles