【问题标题】:How can I only show the JavaScript in particular controller and method?如何仅在特定控制器和方法中显示 JavaScript?
【发布时间】:2012-12-29 20:48:11
【问题描述】:

我有很多模型。现在我想只向特定的控制器和方法展示 JavaScript。

例如,如果我有这样的代码并且只想在 communities/show 中显示它 我应该将其粘贴到 view/communities/show.html.erb 的头部吗?
还是有更聪明的方法来管理这类事情? 显然,如果我把它放在显示文件的头部看起来很丑,因为 JavaScript 总是应该放在 标记中。

<%= javascript_tag do %>
    jQuery(document).ready(function () {
        refreshPartial();
        setInterval(refreshPartial, 5000)
    });


    function refreshPartial() {
      $.ajax({
        url: "<%= community_path %>/refresh_part",
        type: "GET",
        dataType: "script",
      });
    }
<% end %>

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 jquery


    【解决方案1】:

    communities.js

    jQuery(document).ready(function () {
      refreshPartial();
      setInterval(refreshPartial, 5000)
    });
    
    
    function refreshPartial() {
      $.ajax({
        url: "community/refresh_part",
        type: "GET",
        dataType: "script",
      });
    }
    

    查看/communities/show.html.erb

    <%- content_for(:head) do -%>
    <%= javascript_include_tag :communities.js -%>
    <%- end -%>
    

    communities_layout

    <head>
    <title>Merry Christmas!</title>
    <%= yield(:head) -%>
    </head>
    

    【讨论】:

    • 这是最干净的方法,@MKK,你不能在 .js 文件中使用 ruby​​ 变量,但你可以使用 ruby​​ 变量将 coffscript
    • 将communities.js 改为communities.js.coffee 就可以了?
    • 我已经更新了。是的,我们可以将它与 coffscript 一起使用;在这里我们可以将 URL 指定为字符串..
    • 我已经有了 community.js.coffee。我认为它是由脚手架自动创建的。我可以将我的 JS 代码复制并粘贴到那里,包括 ruby​​ 变量吗?
    【解决方案2】:

    有几种方法可以做到这一点

    1. 你的 show.html.erb 的顶部:

      <% content_for :javascript_includes do %>
      <%= javascript_include_tag "forms.js" %>   
      <% end %>
      

      另请参考this answer

    2. Where do you put page specific JavaScript code 看看How Asset Pipeline works

    【讨论】:

      猜你喜欢
      • 2011-11-10
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多