Rails:CoffeeScript或JavaScript资产文件中的访问控制器实例变量 [英] Rails: access controller instance variable in CoffeeScript or JavaScript asset file

查看:180
本文介绍了Rails:CoffeeScript或JavaScript资产文件中的访问控制器实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails 3.1中,不可能使用诸如<%= @foo%>之类的语法访问资源js.erb或coffee.erb文件中的控制器实例变量,其中@foo在控制器中设置。因此,问题是什么是将控制器变量传递给CoffeeScript或JavaScript资产的最佳方法。

In Rails 3.1 it is not possible to access controller instance variables in an asset js.erb or coffee.erb file using syntax such as <%= @foo %>, where @foo is set in the controller. So then the question is what are the best ways for passing controller variables to CoffeeScript or JavaScript assets.

这个问题在论坛上有多种复杂形式的问题,但我的要求是再次提出一个地方,所有的建议都收集在一起,提供的代码是简单和可读的。另请注意,我具体指的是资产,而不是查看响应文件。

This question has kind of been asked in multiple convoluted forms on the forum, but my point in asking it again is to have a place where all recommendations are gathered together, and the code supplied is simple and readable. Also note that I'm specifically referring to assets and not view response files.

推荐答案

过去

将数据放入隐藏字段,访问js / coffee中的数据

put the data in hidden fields, access the data in js/coffee

# single value
<%= hidden_field_tag "foo_name", @foo.name, { :id => "foo-name" } %>
$('#foo-name').val();

# when the 'value' has multiple attributes
<%= hidden_field_tag "foo", @foo.id, { :id => "foo", "data-first-name" => @foo.first_name, "data-last-name" => @foo.last_name } %>
$foo = $('#foo')
console.log $foo.val()
console.log $foo.data("firstName")
console.log $foo.data("lastName")

另一个选项:在erb中将数据加载到js数据结构中,从js / coffee访问它

another option: load data into js data structure in erb, access it from js/coffee

<% content_for(:head) do %>
    <script>
    window.App = window.App || {};
    window.App.Data = window.App.Data || {};
    window.App.Data.fooList = [
        <% @list.each do |foo| %>
            <%= foo.to_json %>,
        <% end %>
    ];
    </script>
<% end %>


# coffee
for foo in window.App.Data.fooList
    console.log "#{foo.id}, #{foo.first_name} #{foo.last_name}"

我不喜欢从ruby中构建JavaScript数据这个问题只是觉得错了 - 它可以是有效的

I am not a big fan of constructing javascript data from ruby in erb like this, something about it just feels wrong - it can be effective though

和另一个选项:进行ajax调用,并从服务器获取数据

and another option: make an ajax call and get the data on-demand from the server

我也对其他想法和方法感兴趣

I am also interested in other ideas and approaches

这篇关于Rails:CoffeeScript或JavaScript资产文件中的访问控制器实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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