“不能找到变量” Rails 3.1和Coffeescript错误 [英] "Can't find variable" error with Rails 3.1 and Coffeescript

查看:73
本文介绍了“不能找到变量” Rails 3.1和Coffeescript错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有视图,引用我的application.js文件,其中包含我在整个应用程序中使用的函数。

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

我刚刚安装了Rails 3.1发布候选使用3.1的边缘版本。直到我安装了RC我没有任何问题,但现在我得到这个错误:

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:找不到变量:indicator_tag

ReferenceError: Can't find variable: indicator_tag

indicator_tag是我在application.js中定义的一个函数。
我在javascript文件中注意到的唯一区别是,现在我的所有函数都包装在:

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.

推荐答案

在默认情况下,每个CoffeeScript文件被编译成一个闭包。您不能与来自其他文件的函数交互,除非将它们导出到全局变量。我建议做这样的事情:

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:

在每个coffeescript文件的顶部,添加一行

On top of every coffeescript file, add a line like

window.Application ||= {}

现在,对于你需要从另一个文件调用的每个函数,将它们定义为

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

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

并使用

Application.indicator_tag(params)

这篇关于“不能找到变量” Rails 3.1和Coffeescript错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆