Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

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

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(this);

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...