如何在Rails 3中导入JavaScript文件?

时间:2023-01-13 17:56:46

I've just started working with Ruby on Rails, and I'm having some difficulty calling JavaScript functions from HTML. I'm using Rails 3.2.13, Ruby 1.9.3, and RubyMine 5.0.2.

我刚刚开始使用Ruby on Rails,我在从HTML调用JavaScript函数时遇到了一些困难。我正在使用Rails 3.2.13,Ruby 1.9.3和RubyMine 5.0.2。

I have a CoffeeScript file called "home.js.coffee" in "app/assets/javascripts/" that apparently compiles to "application.js" in the same folder. In "app/views/home/", I have the HTML file for the home page "index.html.erb". I have a function in "home.js.coffee" called cubes():

我在“app / assets / javascripts /”中有一个名为“home.js.coffee”的CoffeeScript文件,该文件显然编译为同一文件夹中的“application.js”。在“app / views / home /”中,我有主页“index.html.erb”的HTML文件。我在“home.js.coffee”中有一个名为cubes()的函数:

cubes = alert math.cube 3

This is really basic for now. I want to get comfortable first.

这是现在非常基本的。我想先舒服一点。

This is an object called math:

这是一个名为math的对象:

math =
    cube: (x) -> x* square x

I created a button in index.html.erb that should theoretically call this function:

我在index.html.erb中创建了一个理论上应该调用此函数的按钮:

<button onclick="cubes()">Try it</button>

The problem is getting it to find the JavaScript file. What needs to be in index.html's head? What needs to be in application.html's head?

问题是让它找到JavaScript文件。 index.html的头脑需要什么?在application.html的头脑中需要什么?

1 个解决方案

#1


3  

The problem is that the function is in another scope. If you compile the CoffeeScript with the -b option, that will make the functions globally available, but the simple solution would be:

问题是该功能在另一个范围内。如果使用-b选项编译CoffeeScript,这将使函数全局可用,但简单的解决方案是:

root = exports ? this
root.cubes = -> alert math.cube 3

and then you can call cubes() from your HTML.

然后你可以从你的HTML调用cubes()。

#1


3  

The problem is that the function is in another scope. If you compile the CoffeeScript with the -b option, that will make the functions globally available, but the simple solution would be:

问题是该功能在另一个范围内。如果使用-b选项编译CoffeeScript,这将使函数全局可用,但简单的解决方案是:

root = exports ? this
root.cubes = -> alert math.cube 3

and then you can call cubes() from your HTML.

然后你可以从你的HTML调用cubes()。