将全局变量从控制器传递到coffeescript

时间:2014-04-14 18:17:56

标签: ruby-on-rails coffeescript

在我的控制器中,我有一个全局变量@var,它被设置为一个整数,让我们说它等于99.

@var = 99

我特别使用javascript(http://github.hubspot.com/odometer/docs/welcome/)将该变量的值传递给JS函数。我知道我可以轻松地在视图中调用它:

<script type="text/javascript">
  setTimeout(function() {
    odometer.innerHTML = <%= @var %>;
  }, 1000);
</script>

这是糟糕的编程,我宁愿以正确的方式使用coffeescript。如何在CoffeeScript文件中访问此变量?

setTimeout (->
  odometer.innerHTML = var_variable_here
  return
), 1000

2 个答案:

答案 0 :(得分:2)

我推荐你这个宝石:Gon。基本上,在您的控制器中:

@your_int = 123
@your_array = [1,2]
@your_hash = {'a' => 1, 'b' => 2}
gon.your_int = @your_int
gon.your_other_int = 345 + gon.your_int
gon.your_array = @your_array
gon.your_array << gon.your_int
gon.your_hash = @your_hash

您可以从JavaScript文件中访问这些变量:

alert(gon.your_int)
alert(gon.your_other_int)
alert(gon.your_array)
alert(gon.your_hash)

有一个有趣的Railscast,其中有一个详细的例子:Passing Data to JavaScript

答案 1 :(得分:0)

您可以执行以下操作:

setTimeout (->
  odometer.innerHTML = #{ruby_code_here}
  return
), 1000

一位同事在Windows服务器上发现了一些关于CoffeeScript及其中ruby代码使用的内容

sayHello (-> alert("#{ 'Hello' }") )

每次渲染此部件时,Windows服务器都会将CoffeeScript重新编译为JavaScript,以便始终使用ruby变量的正确内容生成javascript。这很有意义,但在Windows机器上,它可能会导致性能问题。

一个简单的解决方法是使用简单的javascript来设置外推变量:

:javascript
  var mystring = #{ "hello" }

:coffeescript
  console.log(mystring)

由于ExecJS或TheRubyRacer,Unix系统上没有性能问题!