开发者

"Can't find variable" error with Rails 3.1 and Coffeescript

开发者 https://www.devze.com 2023-03-07 10:59 出处:网络
I have views in my application that reference my application.js file which contains functions I use throughout my application.

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

I just installed the Rails 3.1 release candidate after having used the edge version of 3.1. Until I installed the RC I wasn't having any problems but now I'm getting this error:

ReferenceError: Can't find variable: indicator_tag

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

(function() { ... }).call(th开发者_如何转开发is);

I understand this is for variable scoping? But could it be preventing my pages from using those variables? And before anyone asks, I've made sure the javascript paths are correct in my include tags.


By default, every CoffeeScript file is compiled down into a closure. You cannot interact with functions from a different file, unless you export them to a global variable. I'd recommend doing something like this:

On top of every coffeescript file, add a line like

window.Application ||= {}

This will ensure that there's a global named Application present at all times.

Now, for every function that you'll have the need to call from another file, define them as

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

and call them using

Application.indicator_tag(params)


Dogbert's solution is a great way to go if you have a very sophisticated JS back-end. However, there's a much simpler solution if you only have a handful of functions you're working with. Just add them directly to the window object, like this:

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

Then you can use your functions from anywhere without having to wrap them up in another object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号